gpt4 book ai didi

javascript - jQuery:如何在类组中查找类的编号位置

转载 作者:行者123 更新时间:2023-11-28 17:58:20 24 4
gpt4 key购买 nike

我有一组img具有相同类的元素。

<!--div of img elements-->
<div id="container">
<img class="square" src="one.jpg"/>
<img class="square" src="two.jpg"/>
<img class="square" src="three.jpg"/>
<img class="square" src="four.jpg"/>
<img class="square" src="five.jpg"/>
</div>

当其中之一 img单击元素后,我想登录到控制台 img 的编号位置。例如,如果 <img class="square" src="two.jpg"/>单击后,我希望控制台记录 2 ,因为该元素是 class="square" 的第二个元素.

我尝试过的

引用this previous Stack Overflow question ,这是我迄今为止在代码中尝试使用的内容:

<!--jquery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script>

//click an image with class="square"
$(".square").click(function() {
//find position of clicked image within classes "square"
console.log( $(this).index('#container') + 1);

</script>

控制台中的结果始终是 0 。我做错了什么?

最佳答案

删除“#container”,它将为您提供容器中元素的索引。

来自 jQuery API 文档:

If no argument is passed to the .index() method, the return value is an integer indicating the position of the first element within the jQuery object relative to its sibling elements.

$(".square").click(function() {
//find position of clicked image within classes "square"
console.log( $(this).index() + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<img class="square" src="one.jpg"/>
<img class="square" src="two.jpg"/>
<img class="square" src="three.jpg"/>
<img class="square" src="four.jpg"/>
<img class="square" src="five.jpg"/>
</div>

关于javascript - jQuery:如何在类组中查找类的编号位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44057985/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com