在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视频教程
以上就是jquery中index()方法怎么用的详细内容。