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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8801787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:34:05  来源:igfitidea点击:

Get index of clicked element using pure javascript

javascriptindexingonclick

提问by Hakan

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?

here is a example of what I am trying to do (it only gives back 6):

这是我正在尝试做的一个例子(它只返回 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>

回答by Ashwin Krishnamurthy

Here is a piece of codethat can help you get the index of the clicked element inside the forloop. All you need is a new scope:

这是一段代码,可以帮助您获取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);

}

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

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

event handler already is a closure

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

Edit 2:Updated fiddle link

编辑 2:更新小提琴链接

回答by MelkorNemesis

With ES6 destructuring you can do

使用 ES6 解构,你可以做到

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

or

或者

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

or ES5 version

或 ES5 版本

var index = Array.prototype.slice.call(el.parentElement.children).indexOf(el)

回答by MelkorNemesis

The accepted answer (from Ashwin Krishnamurthy) is actually far from optimal.

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

You can just do:

你可以这样做:

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

to avoid creating unnecessary closures. And even then it's not optimal since you're creating 6 DOM event handlers (6 divsin the example above) just to get a number of a single clicked div.

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

What you should actually do is use an event delegation (attach singleclick event to the parent) and then check the e.target's index using the method I've mentioned earlier and above (Get index of clicked element using pure javascript).

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

回答by Bergi

Table cell elements have a cellIndexproperty, but I don't know about other elements. You will either have to

表格单元格元素有一个cellIndex属性,但我不知道其他元素。你要么必须

  • create a closure to reserve the value of i
  • dynamically count previousSiblings
  • add an indexproperty in your for-loop and read that (don't augment host objects).
  • 创建一个闭包来保留值 i
  • 动态计数previousSiblings
  • index在 for 循环中添加一个属性并读取它(不要增加宿主对象)。

The closure approach will be the easiest, I think. Please make sure you have understood how closures work, there are good explanations on the web.

我认为关闭方法将是最简单的。请确保您已经了解闭包的工作原理,网上有很好的解释。

function makeAlertNumber(element, i) {
    element.addEventListener('click', function() {
       alert('Number ' + i + ' was clicked');
    }, false);
}
[].slice.call(document.getElementById('container').children).forEach(makeAlertNumber); // homework: find a way to express this for older browsers :-)

回答by RealMJDev

I had the same issue where I needed to loop through an array and get the index number of the item clicked.

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

Here is how I solved the issue...

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

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

//loop through array with forEach function
container.forEach(item => {
    item.addEventListener('click', () => {
        console.log(container.indexOf(item));
    });
});

This will console.log the index number of the item clicked on.

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

Hope this answers some questions.

希望这能回答一些问题。

回答by jAndy

The index in relationship to what ?

该指数与什么有关?

If it is about the index within the current HTML collection, the index would just be represented with your icounter variable.

如果它是关于当前 HTML 集合中的索引,则索引将仅用您的i计数器变量表示。

One word of caution: Since HTMLCollections are "Live", you should ever use them to figure out the .lengthwithin a loop. If it happens to be that those elements are added or removed within the loop, strange and dangerous things can happen. Cache the .lengthvalue before calling the loop instead.

一个警告:由于 HTMLCollections 是“实时的”,您应该使用它们来找出.length循环内的内容。如果碰巧在循环中添加或删除了这些元素,就会发生奇怪和危险的事情。.length在调用循环之前缓存该值。

回答by Akshay Vijay Jain

getIndexOfNode: function(node){ var i = 1; while(node.previousElementSibling != null){ i++ } return i; }
the function will return the index of the node passed in its parent element.

getIndexOfNode: function(node){ var i = 1; while(node.previousElementSibling != null){ i++ } return i; }
该函数将返回传入其父元素的节点的索引。

回答by Jens T?rnell

I made a function to find the index.

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

function index(el) {
  return [...el.parentElement.children].indexOf(el);
}

Call it like this:

像这样调用它:

let index = index(element);