<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>jQuery-位置选择器</title> <script type="text/JavaScript" src="./js/jquery-3.4.1.js"></script> </head> <body> <h2>位置筛选器</h2> <h3>$("selector:first")、$("selector:last")、 $("selector:odd")、$("selector:even")</h3> <div class="div"> <p>第一个:first</p> <p>偶数:even</p> </div> <div class="div"> <p>奇数:odd</p> </div> <div class="div"> <p>偶数:even</p> </div> <div class="div"> <p>奇数:odd</p> </div> <div class="div"> <p>偶数:even</p> </div> <div class="div"> <p>最后一个:last</p> <p>奇数:odd</p> </div> </body> </html> <!-- <script type="text/JavaScript"> //找到第一个div $(".div:first").css("color", "blue"); </script> <script type="text/JavaScript"> //找到最后一个div $(".div:last").css("color", "red"); </script> <script type="text/JavaScript"> //:even 选择所引值为偶数的元素,从 0 开始计数 $(".div:even").css("background", "pink"); </script> <script type="text/JavaScript"> //:odd 选择所引值为奇数的元素,从 0 开始计数 $(".div:odd").css("background", "yellow"); </script> --> <script type="text/JavaScript"> // 第一个 let one=document.querySelector('.div'); console.log(one); one.style.color="blue"; // 最后一个 let last=document.getElementsByClassName('div')[5]; console.log(last); last.style.color="red"; // 偶数行 let ou=document.getElementsByClassName('div'); console.log(ou); for (let i = 0; i < ou.length; i++) { if(i%2==0){ ou[i].style.background="pink"; }else{ ou[i].style.background="yellow"; } }; </script>