简体   繁体   English

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

[英]javascript click event handler fires without clicking

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);
}

You are directly calling it.你直接调用它。

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

You should do that in a callback.你应该在回调中这样做。

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

This code executes your function hideId("main") you should pass just the callback's name:此代码执行您的函数hideId("main")您应该只传递回调的名称:

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

function hideId(event) {
    var id = event.target.srcElement.id; // get the id of the clicked element
    document.getElementById(data).style.display = "none";
    console.log("hidden element #"+data);
}
document.getElementById("main_btn").addEventListener("click", hideId.bind(null, "main");

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

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