我有3个div与类:wpEdit和onClick:alertName()
<div class="wpEdit" onClick="alertName()">Bruce Lee</div>
<div class="wpEdit" onClick="alertName()">Jackie Chan</div>
<div class="wpEdit" onClick="alertName()">Jet li</div>
Run Code Online (Sandbox Code Playgroud)
点击后我想知道点击的Div的类wpEdit的索引:
function alertName(){
//Something like this
var classIndex = this.className.index; // This obviously dosnt work
alert(classIndex);
}
Run Code Online (Sandbox Code Playgroud)
当点击Bruce Lee时它应该警告:0当点击成龙它应该警告:1当点击Jet Li它应该警告:2
我需要知道单击class ="wpEdit"的哪个实例
试试这个
function clickedClassHandler(name,callback) {
// apply click handler to all elements with matching className
var allElements = document.body.getElementsByTagName("*");
for(var x = 0, len = allElements.length; x < len; x++) {
if(allElements[x].className == name) {
allElements[x].onclick = handleClick;
}
}
function handleClick() {
var elmParent = this.parentNode;
var parentChilds = elmParent.childNodes;
var index = 0;
for(var x = 0; x < parentChilds.length; x++) {
if(parentChilds[x] == this) {
break;
}
if(parentChilds[x].className == name) {
index++;
}
}
callback.call(this,index);
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
clickedClassHandler("wpEdit",function(index){
// do something with the index
alert(index);
// 'this' refers to the element
// so you could do something with the element itself
this.style.backgroundColor = 'orange';
});
Run Code Online (Sandbox Code Playgroud)