基础选择器
| <!DOCTYPE html> |
| <html lang="zh-CN"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>Title</title> |
| |
| </head> |
| <body> |
| <div class="nav" id="index"> |
| <a href="">weather</a> |
| |
| </div> |
| <input type="text"> |
| <input type="text" name="username"> |
| <input type="password" name="password"> |
| <script src="jquery-3.7.1.js"></script> |
| <script> |
| $(function() { |
| |
| console.log($('input')); |
| |
| console.log($('.nav')); |
| |
| console.log($('#index')); |
| |
| console.log($('[name="password"]')); |
| |
| }); |
| |
| </script> |
| </body> |
| </html> |
复制
层级选择器
子代选择器:$('ul>li');使用>号,获取亲儿子层级的元素,不会获取孙子层级的元素
后代选择器:$('ul li');使用空格,代表后代选择器,获取ul标签下的所有li元素
| <!DOCTYPE html> |
| <html lang="zh-CN"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>Title</title> |
| |
| </head> |
| <body> |
| <div class="father"> |
| <li>这是标签下的亲儿子</li> |
| |
| <div class="son"> |
| <li>这是div这个儿子的儿子,也就是.father的孙子</li> |
| |
| </div> |
| |
| |
| </div> |
| |
| |
| <script src="jquery-3.7.1.js"></script> |
| <script> |
| $(function() { |
| console.log($('.father li')); |
| console.log($('.father>li')); |
| |
| }); |
| |
| </script> |
| </body> |
| </html> |
复制
伪类选择器
| <!DOCTYPE html> |
| <html lang="zh-CN"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>Title</title> |
| |
| </head> |
| <body> |
| <div class="nav"> |
| <ul> |
| <li>橘子</li> |
| <li>苹果</li> |
| <li>香蕉</li> |
| <li>banana</li> |
| <li>orange</li> |
| </ul> |
| </div> |
| |
| <script src="jquery-3.7.1.js"></script> |
| <script> |
| $(function() { |
| |
| console.log($('ul li:first')); |
| |
| |
| console.log($('ul li:last')); |
| |
| |
| console.log($('ul li:eq(1)')); |
| |
| |
| console.log($('ul li:odd')); |
| console.log($('ul li:even')); |
| }); |
| |
| </script> |
| </body> |
| </html> |
复制
小案例:批量操作
| |
| <!DOCTYPE html> |
| <html lang="zh-CN"> |
| <head> |
| <meta charset="UTF-8"> |
| <title>Title</title> |
| |
| </head> |
| <body> |
| |
| <div> |
| <li>泊船瓜洲</li> |
| <li>王安石</li> |
| <li>京口瓜洲一水间</li> |
| <li>钟山只隔数重山</li> |
| <li>春风又绿江南岸</li> |
| <li>明月何时照我还</li> |
| |
| |
| </div> |
| |
| |
| <script src="jquery-3.7.1.js"></script> |
| <script> |
| $(function() { |
| |
| let odd_list = $('div li:odd') |
| odd_list.css('background','pink') |
| |
| }); |
| |
| </script> |
| </body> |
| </html> |
| |
| |
复制