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

时间:2022-08-17 00:03:16

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

Thanks in advance!

提前致谢!

3 个解决方案

#1


1  

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

#2


1  

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

#3


0  

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

#1


1  

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

#2


1  

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

#3


0  

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