如何获得点击按钮的类(索引)序列号
问题描述:
我需要帮助!如何获得点击按钮的类(索引)序列号
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">
答
尝试此
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>
JS:功能myFunction的(){ VAR键= document.getElementsByClassName( “myButton的”); var index; (var i = 0; i