最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript - find the index of clicked button - Stack Overflow

programmeradmin6浏览0评论

I have N buttons on the page, and I need to find which button is clicked. So far I have this code, which will show the number of buttons, instead of button order:

Fiddle

var nodes = document.getElementsByTagName('button');

for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener('click', function() {
      console.log('You clicked element #' + );

   });
}

I have N buttons on the page, and I need to find which button is clicked. So far I have this code, which will show the number of buttons, instead of button order:

Fiddle

var nodes = document.getElementsByTagName('button');

for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener('click', function() {
      console.log('You clicked element #' + );

   });
}
Share Improve this question edited Mar 28, 2017 at 17:00 Sasha asked Mar 28, 2017 at 16:51 SashaSasha 8,72524 gold badges98 silver badges181 bronze badges 4
  • console.log('You clicked element #' + node[i]); this should work i believe – red security Commented Mar 28, 2017 at 16:53
  • No that wont work, @redsecurity – trincot Commented Mar 28, 2017 at 16:54
  • Oh sorry just put i not node[i] – red security Commented Mar 28, 2017 at 16:54
  • That wont work either, @redsecurity – trincot Commented Mar 28, 2017 at 16:56
Add a ment  | 

3 Answers 3

Reset to default 3

You need to create a closure or use bind, since the value of i will have already reached the final value before you actually click and before the click handler looks up the value of i:

var nodes = document.getElementsByTagName('button');

for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener('click', function(i) {
      console.log('You clicked element #' + i);
   }.bind(null, i));
}

bind will create a copy of the function that has the current value of i bound to it, so it does no harm if i changes by the next iteration.

I don't now if I understand your question, but is this resolve your question?

  var nodes = document.getElementsByTagName('button');

  for (var i = 0, size = nodes.length; i < size; i++) {
    nodes[i].addEventListener('click', function(i) {
      console.log('You clicked element index' + i);
    }.bind(null, i));
  }

jsbin: https://jsbin./podicumeha/1/edit?html,console,output

var nodes = document.getElementsByTagName('button');

for (var i = 0; i < nodes.length; i++) {
   nodes[i].addEventListener('click', function(index) {
      console.log('You clicked element index' + index);
   }.bind(this, i));
}
发布评论

评论列表(0)

  1. 暂无评论