首页 > JavaScript jQuery 中 $(".hot").index($("#favorite")) 这句话是什么意思?

JavaScript jQuery 中 $(".hot").index($("#favorite")) 这句话是什么意思?

这句话我理解不了,是相遇对于谁的位置,他们明明在一个标签里啊!
谁能结合自己的理解跟我说说?

$(".hot").index($("#favorite"))

官方解释:

元素的 index,相对于选择器
获得元素相对于选择器的 index 位置。

该元素可以通过 DOM 元素或 jQuery 选择器来指定。
http://www.w3school.com.cn/jquery/dom_element_methods_index.asp

代码:

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    alert($(".hot").index($("#favorite"))); /*★★★★这里不明白★★★★*/
  });
});
</script>
</head>
<body>
<p>请点击下面的按钮,以获得 id="favorite" 的元素相对于 jQuery 选择器 (class="hot") 的 index:</p>
<button>获得 index</button>
<ul>
<li>Milk</li>
<li class="hot">Tea</li>
<li class="hot" id="favorite">Coffee</li>
</ul>
</body>
</html>

实验改了改,还是1:

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    alert($(".hot").index($("#favorite"))); /*★★★★这里不明白★★★★*/
  });
});
</script>
</head>
<body>
<p>请点击下面的按钮,以获得 id="favorite" 的元素相对于 jQuery 选择器 (class="hot") 的 index:</p>
<button>获得 index</button>
<ul>
<li class="hot">Milk</li>
<li>Tea</li>
<li class="hot" id="favorite">Coffee</li>
</ul>
</body>
</html>

$(".hot")选择的是classhot的标签,也就是

<li class="hot">Tea</li>
<li class="hot" id="favorite">Coffee</li>

index($("#favorite"))是在上面的基础上获得idfavorite的位置,也就是1


$(".hot")一共有几个?2 个。
这两个里面$("#favorite")在第几个?第二个,所以

$(".hot").index($("#favorite"))

就是1(index 从0 开始)

【热门文章】
【热门文章】