如何获取单击按钮的类(索引)序列号

时间:2017-06-18 10:06:24

标签: javascript html css html5 web

我需要帮助!

HTML

<input type="button" onclick="myFunction()" class="myButton" value="Button1">
<input type="button" onclick="myFunction()" class="myButton" value="Button2">
<input type="button" onclick="myFunction()" class="myButton" value="Button3">
<input type="button" onclick="myFunction()" class="myButton" value="Button4">

1 个答案:

答案 0 :(得分:1)

试试这个

var array = document.getElementById('wrapperDiv');

for (var i = 0, len = array.children.length; i < len; i++) {

  (function(index) {
    array.children[i].onclick = function() {
      document.getElementById("indexOfEl").innerText = index;
    }
  })(i);

}
<div id='wrapperDiv'>
  <input type="button" onclick="handleClick()" class="myButton" value="Button1">
  <input type="button" onclick="handleClick()" class="myButton" value="Button2">
  <input type="button" onclick="handleClick()" class="myButton" value="Button3">
  <input type="button" onclick="handleClick()" class="myButton" value="Button4">
</div>
<p>Element index is: <span id="indexOfEl"></span></p>