jquery 第 n 个子点击

标签 jquery html click

我有以下代码:

CSS:

nav div:nth-child(1) { background: red; }
nav div:nth-child(2) { background: blue; }
nav div:nth-child(3) { background: yellow; }

html:

<nav>
 <div>item #1</div>
 <div>item #2</div>
 <div>item #3</div>
</nav>

j查询:

  $(document).ready(function() {

      $('.nav div:nth-child').click(function) {
          console.log(this);
      });

  });

编辑: 我现在得到:未捕获的异常:语法错误,无法识别的表达式::nth-child

如何像CSS那样用jquery点击第n个child并获取item number?例如:我点击第二个,jquery 将返回 2

最佳答案

$(document).ready(function() {
  $('.nav div').click(function() {
      var index = $(this).index();
      console.log(index);
  });
});

索引从零开始

关于jquery 第 n 个子点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8275946/

相关文章:

html - onclick按钮边框颜色改变

javascript - 单击即可使用 jquery 更改 div 的 CSS

JQuery UI Datepicker newDate 减去 2 个月

javascript - 在提交之前验证表单

jquery - 如何使用 jQuery 处理 Primefaces tabView 的 'OnTabShow'?

javascript - 自动缩放内容、标题和其他字体大小

javascript - 拖动时 jQuery mouseleave 未正确触发

html - 限制 HTML5 视频播放次数

jquery - 单击对象时停止 mouseleave

javascript - 从 (click)= 调用多个函数