jQuery中選擇器之子元素篩選器
阿新 • • 發佈:2018-11-10
關於jQuery中選擇器之子元素篩選器相關用法,做以下程式碼驗證:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script src="jquery-3.3.1.js"></script> <title>無標題文件</title> </head> <body> <h2>子元素篩選選擇器</h2> <h3>:first-child、:last-child、:only-child</h3> <div class="left first-div"> <div class="div"> <a>:first-child</a> <a>第二個元素</a> <a>:last-child</a> </div> <div class="div"> <a>:first-child</a> </div> <div class="div"> <a>:first-child</a> <a>第二個元素</a> <a>:last-child</a> </div> </div> <script type="text/javascript"> //查詢class="first-div"下的第一個a元素 //針對所有父級下的第一個 $('.first-div a:first-child').css("color", "#CD00CD"); </script> <script type="text/javascript"> //查詢class="first-div"下的最後一個a元素 //針對所有父級下的最後一個 //如果只有一個元素的話,last也是第一個元素 $('.first-div a:last-child').css("color", "red"); </script> <script type="text/javascript"> //查詢class="first-div"下的只有一個子元素的a元素 $('.first-div a:only-child').css("color", "blue"); </script> <h3>:nth-child、:nth-last-child</h3> <div class="left last-div"> <div class="div"> <a>:first-child</a> <a>第二個元素</a> <a>第三個元素</a> <a>:last-child</a> </div> <div class="div"> <a>:first-child</a> <a>第二個元素</a> </div> <div class="div"> <a>:first-child</a> <a>第二個元素</a> <a>第三個元素</a> <a>:last-child</a> </div> </div> <script type="text/javascript"> //查詢class="last-div"下的第二個a元素 $('.last-div a:nth-child(2)').css("color", "#CD00CD"); </script> <script type="text/javascript"> //查詢class="last-div"下的倒數第二個a元素 $('.last-div a:nth-last-child(2)').css("color", "red"); </script> </body> </html>
驗證結果: