如何知道 class 中的哪个索引被点击

How to know which index in the class is clicked

看着这个 link ,我在想 classes 实际上已经被索引了。如果我有这段代码,我怎样才能在 JavaScript 或 jQuery 中获得所点击按钮的 class 的索引?

<button class="class_name" id="b1"></button>
<button class="class_name" id="b2"></button>

在jquery中: $( "#b1" ).index()

编辑:刚刚看到您的更新,您可以在 jquery 中对按钮点击索引

执行此操作
$('button').click(function (event) {
    alert($(this).index());
});

演示http://jsfiddle.net/mg7zau4c/

jQuery index

Search for a given element from among the matched elements.

$('.class_name').on('click', function(){
    console.log($(this).index());
});

Thanks. How to return the id from this? – Syntactic 7 mins ago

$(this).attr('id');

您可能会想到 NodeList,它由 var nodes = document.querySelectorAll('.class_name') 返回,然后可以执行 nodes.lengthconsole(nodes[1].id) 等操作。

see MDN

没有jQuery:

var index, 
    buttons = document.getElementsByClassName('class_name');
for(var i=0;i<buttons.length;i++){
    buttons[i].onclick = function(){
        for(var j=0;<buttons.length;j++){
             if(buttons[j]==this) {
                 index = j; //console.log(j), etc
                 break;
             }
        }
    }
}

少了一个大括号,还有一个fiddle:

[].slice.call(document.getElementsByClassName('class_name')).forEach(function(o,i,arr){
    o.onclick = function(){
       var index, that = this;
       var search = arr.some(function(b,j){
           index = j;
           return that == b;
       });
       alert(index);
   }
});

NodeLists 总是按顺序排列的,但是如果您重新排序元素,您将不得不再次查询 getElementsByClassName

您可以使用它遍历 children 包含按钮的元素。假设唯一的 children 是有问题的按钮,您可以获得这样的索引。

document.getElementById('buttonContainer').addEventListener('click', function(e) { 
  var clickedButton = e.target, 
      index = -1; 
  [].slice.call(this.children).some(function(el, idx) { 
    if (e.target === el) { 
      index = idx; 
      return true; 
    }
    return false; 
  }); 
  document.getElementById('indexText').textContent = index + ' ' + e.target.id; 
});
<div id="buttonContainer">
<button class="class_name" id="red"></button>
<button class="class_name" id="blue"></button>
<button class="class_name" id="purple"></button>
<button class="class_name" id="magenta"></button>
<button class="class_name" id="rouge"></button>
<button class="class_name" id="cyan"></button>
<button class="class_name" id="yellow"></button>
<button class="class_name" id="black"></button>
  </div>
<p id="indexText"></p>