如何获取 this.id 的 .index()



如果我想使用each()遍历一个类。如何将id附加到该类并获取其索引?

我尝试这样做,但this.id只返回该 id 名称而不是实际 id:

$('.nav-click').each(function() {
console.log($(this.id).index('.nav-click'));
});

您可以使用this来引用元素:

$('.nav-click').each(function() {
console.log(this.id); // the id attribute
console.log($(this).index('.nav-click')); // the index of this element within the .nav-click set
});

或者,您可以使用传递给each()处理程序函数的index参数:

$('.nav-click').each(function(i) {
console.log(i);
});

您可以使用indexattr函数。

$('.nav-click').each(function() {
console.log($(this).index(), $(this).attr('id'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class='nav-click' id='one'>one</p>
<p class='nav-click' id='two'>two</p>

相关内容

最新更新