Get index of clicked element using pure javascript

試著忘記壹切 提交于 2020-01-18 07:07:51

问题


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>

回答1:


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




回答2:


With ES6 destructuring you can do

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

or

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

or ES5 version

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



回答3:


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

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 divs in the example above) just to get a number of a single clicked div.

What you should actually do is use an event delegation (attach single click 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).




回答4:


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

  • create a closure to reserve the value of i
  • dynamically count previousSiblings
  • add an index property in your for-loop and read that (don't augment host objects).

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



回答5:


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 i counter variable.

One word of caution: Since HTMLCollections are "Live", you should ever use them to figure out the .length within 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 .length value before calling the loop instead.




回答6:


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.

Hope this answers some questions.




回答7:


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.



来源:https://stackoverflow.com/questions/8801787/get-index-of-clicked-element-using-pure-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!