当事件触发的时候如何知道这个li是其父辈ul的第几个子元素?
认证高级PHP讲师
jq: xx.index() raw js:
var prev = xx.previousSibling, index = 1; while(prev){ if(prev.nodeType!=1){ prev = prev.previousSibling; continue; } else{ prev = prev.previousSibling; index++; } }
li属于ul的第index个元素。
举个例子:
<ul> <li>123</li> <li id="demo">234</li> <li>345</li> </ul> <script> document.getElementById("demo").onclick = function(event){ var event = event || window.event, e = event.target || event.srcElement, prev = e.previousSibling, index = 1; while(prev){ if(prev.nodeType!=1){ prev = prev.previousSibling; continue; } else { prev = prev.previousSibling; index++; } } console.log(index); // 输出2 } </script>
var arr = event.target.parentElement.children; for(var i=0;i<arr.length;i++) { if(event.target == arr[i]) console.log(i) }
额,有点傻,或许该给li加个data-index属性? event.target.index
jq: xx.index()
raw js:
li属于ul的第index个元素。
举个例子:
额,有点傻,或许该给li加个data-index属性?
event.target.index