jquery中index()方法怎么用

2022-04-02 15:52:59 IT技术网 互联网
浏览

在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>

输出结果:

20.png

点击按钮后:

19.png

相关视频教程推荐:jQuery视频教程

以上就是jquery中index()方法怎么用的详细内容,更多请关注dnjidi.com其它相关文章!