简体   繁体   中英

“OnClick” events created through JavaScript are triggering immediately, not when the object is clicked

Okay. We all know that we could do something like this:

<input type="button" value="Create Button" onclick="addB()"/>
<p id="demo"/>
<script>
function addB() {
var object1 = document.createElement("input");
object1.type="button";
object1.value="Example of value";
document.getElementById("demo").appendChild(object1);
}
</script>

Let's do that again, but modified a little bit. Now we'll add another function and give it another attribute.

<input type="button" value="Create Button" onclick="addB()"/>
<p id="demo"/>
<script>
function addB() {
var object1 = document.createElement("input");
object1.type="button";
object1.value="Example of value";
object1.onclick=myFunction();
document.getElementById("demo").appendChild(object1);
}

function myFunction() {
alert("You have clicked me.");
}
</script>

If you took the time to read the code, then what it's supposed to do is assign that button an onclick attribute so that when you click the generated button, it will trigger a function called "myFunction". But it doesn't do that. It calls the function immediately.

Does anyone know why this is happening or something I'm doing wrong? I would love some help. Thank you very much for your support.

You're calling MyFunction , not assigning it as the event handler, because you're including the brackets. Change the line to

object1.onclick=myFunction;

You shouldn't be calling the function while assigning as attribute.

change following line

object1.onclick=myFunction();

to

object1.onclick=myFunction;

and it should work.

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