本文介绍了使用纯javascript获取被点击元素的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要知道点击元素的索引。无法弄清楚怎么做

I need to know the index of clicked element. Can't figure out how to do it

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

this.index?

this.index?

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

here is a example of what I am trying to do (it only gives back 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>


推荐答案

这是,可以帮助您获取循环内单击元素的索引。您只需要一个新的:

Here is a piece of code that can help you get the index of the clicked element inside the for loop. All you need is a new scope:

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);

}

编辑1:合并用户Felix Kling对答案的评论。

Edit 1: Incorporating user Felix Kling's comments into the answer.

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

这篇关于使用纯javascript获取被点击元素的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:00