简体   繁体   English

调用事件处理程序似乎不起作用

[英]Invoking event handler doesn't seem to work

I have this code for collapsible items.我有可折叠物品的代码。

var coll = document.getElementsByClassName("collapsible");

for (var i = 0; i < coll.length; i++) {
    coll[i].addEventListener("click", function() {        
        this.classList.toggle("active");
        var p = this.nextElementSibling;
        if (p.style.maxHeight){
            p.style.maxHeight = null;
        } else {
            p.style.maxHeight = p.scrollHeight + "px";
        } 
    });
    if (window.screen.availWidth >= 768) coll[i].onclick.apply(coll[i]);
}

The last line is meant to automatically expand all collapsibles on larger screens.最后一行是为了在更大的屏幕上自动展开所有可折叠项。 But it gives me an error:但它给了我一个错误:

Uncaught TypeError: Cannot read property 'apply' of null

How can I fix this?我怎样才能解决这个问题?

coll[i].onclick is null, onclick is an event not a function, so you would like to use click function there. coll[i].onclick is null, onclick is an event not a function, so you would like to use click function there.

Not sure what are you trying to achieve by passing coll[i] as this for click function.不知道你想通过传递 coll[i] 来实现点击 function。 but try:但尝试:

coll[i].click.apply()

or simpler:或更简单:

coll[i].click()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM