Javascript 父元素的哪个子元素号是子元素-这是属性吗?

Javascript 父元素的哪个子元素号是子元素-这是属性吗?,javascript,parent-child,Javascript,Parent Child,三个分区: 一个 两个 三 单击时,它们会报告它们在父元素中的子编号: 函数whatAmI(源代码){ //此函数告诉您孩子是哪个数字 //在父元素中嵌套的所有内容中 对于(x=0;x如果您所处的环境支持(例如,现代浏览器,包括IE9+或node.js),您可以使用它而不是whatAmI: container = document.getElementById('container') for(x=0;x<container.children.length;x++){ cont

三个分区:


一个
两个
三
单击时,它们会报告它们在父元素中的子编号:

函数whatAmI(源代码){
//此函数告诉您孩子是哪个数字
//在父元素中嵌套的所有内容中

对于(x=0;x如果您所处的环境支持(例如,现代浏览器,包括IE9+或node.js),您可以使用它而不是
whatAmI

container = document.getElementById('container')
for(x=0;x<container.children.length;x++){
    container.children[x].addEventListener('click', function(){
        alert(Array.prototype.indexOf.call(container.children, this))
    });
}

我想您正在寻找jQuery的
索引方法


根据他们的说法,这里有一个JSFIDLE:

这个问题没有提到jQuery。没错,但是一个有效的、简洁的替代方案有什么问题吗?我的猜测是,因为他使用的是标记,所以他很可能有jQuery,尽管没有明确说明。不,没有jQuery.Javascript,整洁:DWow,这太棒了。特别是第二个片段-would从未想到过这一点!@LittleBobbyTables在使用ajax填充容器时非常有用。例如,如果您有一个
,其中
  • 元素是动态添加或删除的,您可以向ul添加一个单击处理程序并完成它;如果您没有,则必须附加新的事件处理程序s添加到您添加的每个列表项,即添加它们的那一刻。
    
    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)
                  })
    }
    
    container = document.getElementById('container')
    for(x=0;x<container.children.length;x++){
        container.children[x].addEventListener('click', function(){
            alert(Array.prototype.indexOf.call(container.children, this))
        });
    }
    
    container = document.getElementById('container')
    container.addEventListener('click', function(e){
        alert(Array.prototype.indexOf.call(container.children, e.target));
    });