方法一、
window.onload=function(){
//寻找对象在父元素下的index
function getIndexParent(element){
var oParent=element.parentNode;
var oElement=oParent.children;
for(var i=0;i<oElement.length;i++){
oElement[i].index=i
}
alert(element.index);
}
getIndexParent(document.getElementById('zero')); //return 4
getIndexParent(document.getElementById('one')); //return 1
}
<ul>
<span id='span1'></span>
<li id='one'>1</li>
<li id='two'>2</li>
<li id='zero'>0</li>
<li id='four'>4</li>
</ul>
方法二、
//注意这里是具体的HTML元素,li为HTMLLIElement;div为HTMLDivElement;span为HTMLSpanElement
//寻找对象在父元素下的index
Object.prototype.__defineGetter__("indexOfParent",function(){
var oParent=this.parentNode;
var oElement=oParent.children;
for(var i=0;i<oElement.length;i++){
oElement[i].index=i
}
return this.index;
});
alert(document.getElementById('span1').indexOfParent);