onclick event fires before button clicked - javascript

二次信任 提交于 2019-12-10 07:27:34

问题


I have a pop up window with a button. When I click the button I want something to happen, say an alert.

The issue I am having is that the onclick event fires as soon as the popup is launched and not when the button is clicked.

Here is the code. Any thoughts will be much appreciated.

var popup = open("", "Popup", "width=300,height=200");
var btn = popup.document.createElement("button");
btn.style.height = "50px";
btn.style.width = "150px";
popup.document.body.appendChild(btn);

btn.innerHTML="button1";
btn.onclick = alert("hello");

回答1:


In your code

btn.onclick = alert("hello");

onclick is not fired. Just alert is executed immediately. You should wrap it into a function:

btn.onclick = function(){ alert("hello");}



回答2:


assign function to the btn.onclick event.



来源:https://stackoverflow.com/questions/17351853/onclick-event-fires-before-button-clicked-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!