需要从元素数组中获取元素的索引号
<input type="button" name="test" value="test" onclick="getindex(this)"> <!--index 0-->
<input type="button" name="test" value="test" onclick="getindex(this)"> <!--index 1-->
<input type="button" name="test" value="test" onclick="getindex(this)"> <!--index 2-->
<input type="button" name="test" value="test" onclick="getindex(this)"> <!--index 3-->
...
<script>
function getindex(obj) {
var i = obj.index; //here is wrong. How to get index?
}
</script>
最佳答案
更改页面时不太容易出现问题的方法是将值分配给数据属性:
<input type="button" name="test" value="test" onclick="getindex(this)" data-index="0">
<input type="button" name="test" value="test" onclick="getindex(this)" data-index="1">
<input type="button" name="test" value="test" onclick="getindex(this)" data-index="2">
<input type="button" name="test" value="test" onclick="getindex(this)" data-index="3">
然后从该数据属性中检索索引:
<script>
function getindex(obj) {
var i = parseInt(obj.dataset.index,10);
}
</script>
关于JavaScript : How to get a name of an element index?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44127152/