Onclick按钮不起作用

时间:2013-08-23 15:55:28

标签: javascript html

我尝试在加载页面时创建一个按钮。

<!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>

按钮是成功创建的,但是我与onClick事件关联的功能不起作用。任何想法?

2 个答案:

答案 0 :(得分:5)

onclick需要一个函数,而不是字符串:

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

请参阅此jsFiddle

当然,您应该知道document.write()完全清除所有当前内容的DOM,而不是简单地将字符串附加到现有内容。

答案 1 :(得分:1)

您正在为函数指针指定一个字符串:

更改:

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

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