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

查看:155
本文介绍了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")一共有几个?2 个。
这两个里面$("#favorite")在第几个?第二个,所以

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

就是1(index 从0 开始)

这篇关于JavaScript jQuery 中 $(&quot;.hot&quot;).index($(&quot;#favorite&quot;)) 这句话是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆