jquery nth-child点击

E.G*_*.G. 26 jquery html5 click

我有以下代码:

CSS:

nav div:nth-child(1) { background: red; }
nav div:nth-child(2) { background: blue; }
nav div:nth-child(3) { background: yellow; }
Run Code Online (Sandbox Code Playgroud)

HTML:

<nav>
 <div>item #1</div>
 <div>item #2</div>
 <div>item #3</div>
</nav>
Run Code Online (Sandbox Code Playgroud)

jQuery的:

  $(document).ready(function() {

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

  });
Run Code Online (Sandbox Code Playgroud)

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

如何使用jquery单击nth-child并获取像CSS这样的项目编号?例如:我点击第二个,jquery将返回2

hop*_*rim 36

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

index是从零开始的

  • 请使用`var`:`var index = $(this).index()+ 1;`以避免污染全局命名空间. (7认同)