javascript click event handler fires without clicking

前端 未结 3 1504
礼貌的吻别
礼貌的吻别 2020-12-04 02:12

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 obvi

3条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 02:49

    This code executes your function hideId("main") you should pass just the callback's name:

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

提交回复
热议问题