子元素过滤选择器

    xiaoxiao2025-05-19  8

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>子元素过滤选择器</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> //记得引入<span style="font-family: Arial, Helvetica, sans-serif;">jquery-1.11.3.js文件到js目录下,否则没效果</span> <script type="text/javascript" src="js/jquery-1.11.3.js"></script> <style type="text/css"> body{ font-family: "Microsoft YaHei" } .cGreen{color: #4CA902} .cPink{color: #ED4A9F} .cBlue{color: #0092E7} .cCyan{color: #01A6A2} .cYellow{color: #DCA112} .cRed{color: #B7103B} .cPurple{color: #792F7C} .cBlack{color: #110F10} .cOrange{color: #FF4500} .cGray{color: #A9A9A9} .hide{display: none;} span { float:left; } ul{ } ul li { width:120px; float: left; } </style> <script type="text/javascript"> $(document).ready(function(){ // 给id是btn1的按钮添加点击事件 $("#btn1").click(function(){ // 不是子元素选择; 选择是整个页面的第一个li,添加样式 //$("ul li:first").addClass("cOrange"); // :nth-child()选取ul的第二个(从1开始)li元素 $("ul li:nth-child(1)").addClass("cOrange"); }); $("#btn2").click(function(){ // 选取奇数 $("ul li:nth-child(odd)").addClass("cOrange"); }); $("#btn3").click(function(){ // 选取ul的第3n(n从1开始)个li元素 //$("ul li:nth-child(3n)").addClass("cOrange"); // 只会选择3的倍数 // 选取第1、4、7个 $("ul li:nth-child(3n+1)").addClass("cOrange"); }); $("#btn4").click(function(){ // 选取第一个子元素 $("ul li:first-child").addClass("cOrange"); }); $("#btn5").click(function(){ // 选取最后一个子元素 $("ul li:last-child").addClass("cOrange"); }); $("#btn6").click(function(){ // 选取有唯一子元素 $("ul li:only-child").addClass("cOrange"); }); }); </script> </head> <body> <span>中国城市:</span><br> <ul id="chn"> <li id="bj">北京</li> <li id="sh">上海</li> <li id="gz">广州</li> <li id="sz">深圳</li> <li id="hk">香港</li> </ul> <br><br> <span>美国城市:</span><br> <ul id="usa"> <li id="wst">华盛顿特区</li> <li id="ny">纽约</li> <li id="la">洛杉矶</li> <li id="scg">芝加哥</li> </ul> <br><br> <span>德国城市:</span><br> <ul id="ger"> <li id="mnh">慕尼黑</li> </ul> <div style="clear:both;"></div> <br><br> <hr> <input type="button" id="btn1" value=":nth-child()选取ul的第二个(从1开始)li元素"> <input type="button" id="btn2" value=":nth-child()选取ul的第奇数个li元素"> <input type="button" id="btn3" value=":nth-child()选取ul的第3n(n从1开始)个li元素"> <input type="button" id="btn4" value=":first-child选取ul第一个li元素"> <input type="button" id="btn5" value=":last-child选取ul最后一个li元素"> <input type="button" id="btn6" value=":only-child选取ul中只有唯一li元素"> </body> </html>

    效果如下

    转载请注明原文地址: https://ju.6miu.com/read-1299036.html
    最新回复(0)