javascript click 事件处理程序在不点击的情况下触发

2022-01-15 00:00:00 function event-handling click javascript

为什么这个函数在没有点击指定按钮的情况下被触发?我看了一些类似的问题,但没有一个处理这个代码结构(可能是我失踪的明显原因......).

Why does this function get fired without having clicked on the specified button? I had a look at a few similar problems but none deal with this code structure (might be obvious reason for this im missing...).

document.getElementById("main_btn").addEventListener("click", hideId("main");

function hideId(data) {
    document.getElementById(data).style.display = "none";
    console.log("hidden element #"+data);
}

推荐答案

你是直接调用它.

document.getElementById("main_btn").addEventListener("click", hideId("main");

你应该在回调中这样做.

You should do that in a callback.

document.getElementById("main_btn").addEventListener("click", function (){
    hideId("main");
});

相关文章