jQuery 篩選遍歷
jQuery 中的篩選方法包括 eq()、filter()、not() 等。我們在此處來看其中一些方法 −
not() 方法
jQuery 中的 not() 方法用於返回不符合具體條件的元素。
示例
讓我們看一個示例來實現 jQuery not() 方法 −
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("h2").not(".demo").css("color", "orange"); }); }); </script> <style> h2 { color: blue; } </style> </head> <body> <h2>Student Info</h2> <p>This is a demo text.</p> <h2 class="demo">Exam Info</h2> <p>This is a demo text.</p> <h2 class="demo">Teacher's Info</h2> <p>This is a demo text.</p> <button>Click me</button> </body> </html>
輸出
這將產生以下輸出 −
現在,單擊“點選我”以更新不符合具體條件的元素的文字顏色 −
eq() 方法
jQuery 中的 eq() 方法用於選擇具有特定索引號的元素。索引號從 0 開始。
語法
語法如下 −
$(":eq(index)")
上述程式碼中,引數 index 是元素的索引。
示例
我們現在看一個示例來實現 jQuery eq() 方法 −
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ $("p:eq(2)").css("color", "orange"); }); }); </script> </head> <body> <h2>Student Info</h2> <p>This is a demo text.</p> <h2>Exam Info</h2> <p>This is a demo text.</p> <h2>Teacher's Info</h2> <p>This is a demo text.</p> <button>Click me</button> </body> </html>
輸出
這將產生以下輸出 −
單擊“點選我”以更改特定標題的標題顏色 −
廣告