如果我想使用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);
});
您可以使用index
和attr
函数。
$('.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>