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

标签 javascript jquery

如果我想使用 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);
});

关于javascript - 如何获取 this.id 的 .index(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45152008/

相关文章:

javascript - 在javascript中读取cookie,由asp.net c#code制作

javascript - 带有身份验证登录页面的 angular2 应用程序

javascript - 动态创建 DIV,不是动态获取高度和宽度

javascript - 如何重置drillUpButton 单击时的大小

javascript - 使用单引号将参数传递给函数

javascript - 在触摸屏上滚动会显着减慢 Chrome 上的 AJAX 下载时间

javascript - Facebook Like 按钮在使用 jQuery 初始化时不起作用?

jquery - PHP网站仅在查询时传递特定信息

javascript - 根据 data-* 属性过滤选择选项

jquery - 如何识别 ul 中的哪个 li 具有特定的类?