u和v的值正确显示为1和0 ...,但是语句“ t[i].children[v].onclick=function(){}”中未使用这些值。
当我在u处使用1并在v处使用0时,这非常有效!
这是代码:

    <div class="dropdown">
    <span class="menu-toggler">Menu</span>
    <ul class="dropdown-menu">
    <li>First Part</li>
    <li>Second Part</li>
    </ul>
</div>



<script type="text/javascript">

function init()
{
    t = document.getElementsByClassName("dropdown");
    for(i=0;i<t.length;i++)
    {
        v = getMenuToggler(t[i]); // v is becoming 0 correctly
        u = getDropDown(t[i]); // u is becoming 1 correctly
 // the next statement is not working properly!!!
        t[i].children[v].onclick=function(){if(this.parentNode.children[u].classList.contains("menu-

open")){this.parentNode.children[u].classList.remove("menu-open");}else{this.parentNode.children

[u].classList.add("menu-open");}}
    }
}

function getDropDown(x) // this function is all right... u can ignore this
{
    for(i=0;i<x.childElementCount;i++)
    {
        if(x.children[i].classList.contains("dropdown-menu"))
        return i;
    }
    return -1;
}

function getMenuToggler(y) //this function is all right... u can ignore this
{
    for(i=0;i<y.childElementCount;i++)
    {
        if(y.children[i].classList.contains("menu-toggler"))
        return i;
    }
    return -1;
}
</script>
<script>window.onload=init;</script>


先感谢您... :)

最佳答案

window.onload=init();


如果您这样编写,则会立即调用init而不是分配为事件监听器的函数。

您想要的是:

window.onload=init;


或者以更加标准化和现代的方式:

window.addEventListener('load',init);


如果您像在原始代码中一样错误地过早调用init,则表明DOM尚未加载,因此您无法获取任何元素。

现在,在您为onclick属性分配的功能中,t[i]不会在您编写t[i].children[1]时定义。

由于该函数已分配给onclickt[i].children[0]属性,因此可以将t[i].children[1]替换为this.parentNode.children[1],这等效。

关于javascript - 在javascript中使用元素集合数组中的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29594181/

10-14 15:37
查看更多