2017-06-18 22 views
-1

我需要幫助!如何獲得點擊按鈕的類(索引)序列號

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"> 
+0

JS:功能myFunction的(){ VAR鍵= document.getElementsByClassName( 「myButton的」); var index; (var i = 0; i

回答

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>