在jquery中,index()方法用于返回指定元素相對于其他指定元素的index位置,或者獲得元素相對于選擇器的index位置,語法為“$(selector).index()”或“$(selector).index(element)”。
本教程操作環境:windows10系統、jquery3.2.1版本、Dell G3電腦。
jquery中index()方法怎么用
index() 方法返回指定元素相對于其他指定元素的 index 位置。
這些元素可通過 jQuery 選擇器或 DOM 元素來指定。
Query 里面 提供了一個 index() 方法
搜索與參數表示的對象匹配的元素,并返回相應元素的索引值值。
如果找到了匹配的元素,從0開始返回;如果沒有找到匹配的元素,返回-1。
獲得第一個匹配元素相對于其同級元素的 index 位置。
語法
$(selector).index()
獲得元素相對于選擇器的 index 位置。
該元素可以通過 DOM 元素或 jQuery 選擇器來指定。
語法
$(selector).index(element)
示例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>123</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){ $("button").click(function(){ alert($(".hot").index($("#favorite"))); }); }); </script> </head> <body> <p>單擊按鈕來獲得id =“favorite”的元素的索引,相對于jQuery選擇器(類=“hot”):</p> <button>獲取下標</button> <ul> <li>Milk</li> <li class="hot">Tea</li> <li class="hot" id="favorite">Coffee</li> </ul> </body> </html>
輸出結果:
點擊按鈕后:
相關視頻教程推薦:jQuery視頻教程