JavaScript jQuery 中 $(".hot").index($("#favorite")) 这句话是什么意思?
怪我咯
怪我咯 2017-04-11 09:23:27
[JavaScript讨论组]

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

$(".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>
怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(2)
伊谢尔伦

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

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

就是1(index 从0 开始)

天蓬老师

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

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

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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号