三个div:
<div id='container'> <div id='one'>One</div> <div id='two'>Two</div> <div id='three'>Three</div> </div>
单击时,它们会报告它们在父元素中的子编号:
function whatAmI(source){ //this function tells you which number the child is //in everything nested in the parent element for(x=0;x<source.parentElement.children.length;x++){ if(source.parentElement.children[x]==source){ return alert("I am child #" + x); } } } container = document.getElementById('container') for(x=0;x<container.children.length;x++){ container.children[x].addEventListener('click', function(){ return whatAmI(this) }) }
这真的是一种迂回的做事方式吗?通过迭代父级。肯定有更好的财产吗?
JSFiddle:http: //jsfiddle.net/H9aLf/