问题
I have a few elements with identical class names.
How can I get the number of the elements which I clicked with onclick
events?
For example:
var x = document.getElementsByClassName("myclass").length;
for (a=0; a<=x; a++)
{
// here i want get number of clicked myclass
}
回答1:
You can use indexOf
on an array of document.getElementsByClassName("myclass")
. You can use Array.from
or [].slice.call
to make the array.
Assuming your click
handlers look like in the snippet below and they “Do something to e.target
” where e.target
is the element that has been clicked, you can check the indexOf
e.target
on the array like this:
document.addEventListener("click", function(e) {
if (e.target.classList.contains("myclass")) {
/*
The above part could as well look like
div1.onclick = function(e){…};
div2.onclick = function(e){…};
…
*/
console.log("Do something to %o", e.target);
console.log("Index of clicked element: %d", Array.from(document.getElementsByClassName("myclass")).indexOf(e.target));
}
});
<div>
<div class="myclass">A0</div>
<div>B1</div>
<div class="myclass">A2</div>
</div>
<div>
<div>B3</div>
<div class="myclass">A4</div>
</div>
<div class="myclass">A5</div>
<div class="myclass">A6</div>
<div>B7</div>
<div class="myclass">A8</div>
If you want the index of the element within the same parent element, you can instead use:
Array.from(e.target.parentNode.children).indexOf(e.target)
If you want to restrict the above to elements with the myclass
class, you can use something like:
Array.from(e.target.parentNode.getElementsByClassName("myclass")).indexOf(e.target)
Or for direct children:
Array.from(e.target.parentNode.children).filter(function(elem){
return elem.classList.contains("myclass");
}).indexOf(e.target)
回答2:
You can capture info about the clicked element in the onClick event handler.
Whatever function runs when he click event happens will be passed an event as the first parameter. That event object has a target which will be a reference to the specific element that was clicked.
function clickHandler(event) {
console.log(event.target);
}
来源:https://stackoverflow.com/questions/41193536/what-can-i-get-number-of-clicked-element