gpt4 book ai didi

javascript - 如何获取点击按钮的类(索引)序号

转载 作者:行者123 更新时间:2023-11-28 17:14:20 27 4
gpt4 key购买 nike

我需要帮助!

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>

关于javascript - 如何获取点击按钮的类(索引)序号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44613870/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com