假设我有相同类的元素,但是这些元素封装在不同的父div中。如何找到每个.child div的索引?
如果我要在迭代器中调用索引,我将返回0,因为它是父div中存在的唯一的.child。我想要做的是在#container div范围内获取那些div的索引。
$(function() {
$("#container .child").text(function() {
var i = $(this).index();
return "The index of this element is " + i
});
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<div id="one">
<div class="child"></div>
<div>
<div id="two">
<div class="child"></div>
<div>
<div id="three">
<div class="child"></div>
<div>
</div>
发布于 2015-04-26 18:33:11
如果要使用index,可以使用选择器,然后传入元素以获取集合中的索引。
$("#container .child").index(this)甚至相反的情况
$(this).index("#container .child")但最简单的方法是只在text()的回调函数中使用迭代器
$("#container .child").text(function(i) {
return "The index of this element is " + i
});发布于 2015-04-26 18:26:17
传递给.text()方法的回调函数的第一个参数是当前集合中的索引。
$(function() {
$("#container .child").text(function(i) {
return "The index of this element is " + i
});
});https://stackoverflow.com/questions/29881611
复制相似问题