使用纯 JavaScript 获取点击元素的索引

2023-12-05

我需要知道单击元素的索引。不知道该怎么做

for (i = 0; i < document.getElementById('my_div').children.length; i++) {
    document.getElementById('my_div').children[i].onclick = function(){'ALERT POSITION OF CLICKED CHILD'};
}

这个.index?

这是我想要做的一个例子(它只返回 6):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Untitled Document</title>
<style type="text/css">
body{margin:0;}
#container div{height:50px;line-height:50px; text-align:center}
</style>
</head>
<body>
<div id="container">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<script>
for (i = 0; i < document.getElementById('container').children.length; i++) {
    document.getElementById('container').children[i].onclick = function(){alert('Number ' + i + ' was clicked')};
}
</script>
</body>
</html>

通过 ES6 解构,你可以做到

const index = [...el.parentElement.children].indexOf(el)

or

const index = Array.from(el.parentElement.children).indexOf(el)

或ES5版本

var index = Array.prototype.slice.call(el.parentElement.children).indexOf(el)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用纯 JavaScript 获取点击元素的索引 的相关文章

随机推荐