无法在document.write元素之前将属性'onclick'设置为null

时间:2018-06-23 23:14:52

标签: javascript

我在做什么错?如果这是重复的问题,请重定向至正确的问题,因为我找不到任何有关此问题的信息。

就这么简单:

我收到此错误: “ 未捕获的TypeError:无法将属性'onclick'设置为null

在这段超简单的代码中:

window.onload = function() {
  document.write('<input id="a" type="button" value="This is a button :)">');
  document.getElementById("a").onclick = alert("a");
}

这怎么可能? 问候。

2 个答案:

答案 0 :(得分:0)

将按钮单击后将代码放入要运行的函数中,将使Javascript将该函数与用户的操作“连接”。

window.onload = function() {
       document.write('<input id="a" type="button" value="This is a button :)">');
       document.getElementById("a").onclick = function() {
          alert("a");
       };
    }

否则,您可以使用代码中已定义的另一个函数来代替创建新函数,而是将onclick event =设置为不带括号的函数,如下所示。

function whenYouClick() {
	alert("a");
}

window.onload = function() {
document.write('<input id="a" type="button" value="This is a button :)">');
document.getElementById("a").onclick = whenYouClick;
}

答案 1 :(得分:-1)

代替您的代码:

window.onload = function() {
  document.write('<input id="a" type="button" value="This is a button :)">');
  document.getElementById("a").onclick = alert("a");
}

您可以使用:

window.onload = function() {
  document.write('<input id="a" type="button" value="This is a button :)">');
  document.getElementById('a').setAttribute('onclick','alert(0)');
}