使用纯javascript获取点击元素的索引 [英] Get index of clicked element using pure javascript

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

问题描述

我需要知道被点击元素的索引.不知道怎么做

for (i = 0; i 

this.index?

这是我正在尝试做的一个例子(它只返回 6):

<头><meta charset="utf-8"/><title>无标题文档</title><style type="text/css">正文{边距:0;}#container div{height:50px;line-height:50px;文本对齐:居中}</风格><身体><div id="容器"><div>1</div><div>2</div><div>3</div><div>4</div><div>5</div><div>6</div>

<脚本>for (i = 0; i

解决方案

这是一段代码可以帮助你在 for 循环中获取被点击元素的索引.您只需要一个新的范围:

var g = document.getElementById('my_div');for (var i = 0, len = g.children.length; i < len; i++){(功能(索引){g.children[i].onclick = function(){警报(索引);}})(一世);}

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

<块引用>

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

编辑 2:更新小提琴链接

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?

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

}

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

event handler already is a closure

Edit 2: Updated fiddle link

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆