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

Hak*_*kan 23 javascript indexing onclick

我需要知道clicked元素的索引.无法弄清楚该怎么做

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

this.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>
Run Code Online (Sandbox Code Playgroud)

Ash*_*thy 38

这是一段代码,可以帮助您获取for循环内单击元素的索引.您只需要一个新范围:

var g = document.getElementById('my_div');
for (var i = 0, len = g.children.length; i < len; i++)
{

    (function(index){
        g.children[i].onclick = function(){
              alert(index)  ;
        }    
    })(i);

}
Run Code Online (Sandbox Code Playgroud)

编辑1:将用户Felix Kling的评论纳入答案.

事件处理程序已经是一个闭包

编辑2:更新了小提琴链接

  • 严格来说,事件处理程序已经**是一个闭包.OP需要的是一个新的范围. (3认同)

Mel*_*sis 33

有了ES6解构,你就可以做到

const index = [...el.parentElement.children].indexOf(el)
Run Code Online (Sandbox Code Playgroud)

要么

const index = Array.from(el.parentElement.children).indexOf(el)
Run Code Online (Sandbox Code Playgroud)

或ES5版本

var index = Array.prototype.slice.call(el.parentElement.children).indexOf(el)
Run Code Online (Sandbox Code Playgroud)


Mel*_*sis 7

公认的答案(来自 Ashwin Krishnamurthy)实际上远非最佳。

你可以这样做:

const g = document.getElementById('my_div');
for (let i = 0, len = g.children.length; i < len; i++)
{
    g.children[i].onclick = function(){
        alert(index)  ;
    }
}
Run Code Online (Sandbox Code Playgroud)

以避免创建不必要的关闭。即便如此,这也不是最佳选择,因为您创建 6 个 DOM 事件处理程序(divs在上面的示例中为6 个)只是为了获得一些单击div.

你真正应该做的是使用一个事件代表团(附点击事件父),然后检查e.target使用我前面和上面提到的方法的指数(使用纯JavaScript获得点击元素的索引)。


Mic*_*tto 5

我遇到了同样的问题,我需要循环遍历数组并获取单击的项目的索引号。

这是我解决问题的方法...

//first store array in a variable
let container = [...document.getElementById('container')];

//loop through array with forEach function
container.forEach((item,index) => {
    item.addEventListener('click', () => console.log(index));
});
Run Code Online (Sandbox Code Playgroud)

这将在 console.log 中记录所单击项目的索引号。

希望这能回答一些问题。


Jen*_*ell 5

我做了一个函数来查找索引。

function getElementIndex(el) {
  return [...el.parentElement.children].indexOf(el);
}
Run Code Online (Sandbox Code Playgroud)

像这样称呼它:

const index = getElementIndex(element);
Run Code Online (Sandbox Code Playgroud)