简体   繁体   中英

Onclick button doesn't function

i try to create a button when the page is load.

<!DOCTYPE html>
<html>
<head>
<script>
function createButton(){
var newButton = document.createElement("button");
newButton.onclick="document.write('Tasto premuto')";
var textButton = document.createTextNode("Premi qui");
newButton.appendChild(textButton);
document.body.appendChild(newButton);
}
</script>
</head>
<body onload="createButton()">

</body>
</html>

the button is created succesfully, but the function that I have associated with onClick event doesn't work. any ideas?

onclick expects a function, not a string:

newButton.onclick = function() { document.write('Tasto premuto') };

Please see this jsFiddle

Of course, you should be aware that document.write() completely clears the DOM of all current content, rather than simply appending the string to the existing content.

You're assigning a string to function pointer:

Change:

newButton.onclick="document.write('Tasto premuto')";

To:

newButton.onclick= function(){ document.write('Tasto premuto') };

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