简体   繁体   中英

Trouble adding onclick events in JavaScript

Every time I try to add an onclick event to a newly created button, the event seems to get triggered before the button is even pressed. Here is how I've been trying to go about it:

var que = document.createElement("BUTTON");
var text = document.createTextNode("Question1");
que.appendChild(text);
document.body.appendChild(que);
que.setAttribute("onclick", function1());

Each time function1() is run before I even have a chance to press the button. Does anyone have any ideas of why?

Try this:

que.setAttribute("onclick",function() {function1();})

or this:

que.onclick = function() {function1();}

It should be que.setAttribute("onclick", "function1()");

See fiddle: https://jsfiddle.net/free_soul/L5s1x1nz/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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