简体   繁体   English

Onclick按钮不起作用

[英]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. 该按钮创建成功,但是与onClick事件关联的功能不起作用。 any ideas? 有任何想法吗?

onclick expects a function, not a string: onclick需要一个函数,而不是字符串:

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

Please see this jsFiddle 请看这个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. 当然,您应该知道document.write()完全清除所有当前内容的DOM,而不是简单地将字符串附加到现有内容上。

You're assigning a string to function pointer: 您正在为函数指针分配一个字符串:

Change: 更改:

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

To: 至:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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