使用内联onclick获取类元素的索引-纯js无jQuery
问题描述:
所以我有一些类元素:
<span class="show" onclick="show()">show</span>
<span class="show" onclick="show()">show</span>
<span class="show" onclick="show()">show</span>
当我单击这些元素之一时,出于某种原因我需要索引。我知道如何使用jQuery,但这不是我想要的,在这里。
when i click one of these elements i need the index for some reason. i know how to use jQuery, but thats not what i am asking for, here.
我的js函数应如下所示:
my js function should look something like this:
function show() {
var index = document.getElementsByClassName('show')[??];
alert(index);
}
使用纯JavaScript怎么可能? 注意:我必须坚持不能更改的onclick = show() 。
How is that possible with pure javascript? NOTE: i have to stick with the onclick="show()" that cannot be changed.
我希望有人可以提供帮助,谢谢advance:)
i hope someone can help, thanks in advance :)
答
只需获取所有元素的数组并找到收到点击的当前元素
Just get the array of all the elements and find the current element who received the click
function show(el) {
var els = Array.prototype.slice.call( document.getElementsByClassName('show'), 0 );
console.log(els.indexOf(event.currentTarget));
}
<span class="show" onclick="show(this)">span 1</span>
<span class="show" onclick="show(this)">span 2</span>
<span class="show" onclick="show(this)">span 3</span>