【发布时间】:2021-04-29 16:20:55
【问题描述】:
我创建了一个简单的项目,在该项目中单击一个按钮,然后应该创建另一个按钮(按钮 2),并且前一个按钮应该消失,这工作正常。 但是当我点击按钮 2 时,应该执行一个特定的功能。我被困在这里了。
It says cannot set property to null.
function myFunction1() {
var x = document.createElement("BUTTON");
var t = document.createTextNode("button 2");
x.setAttribute('id','bt2');
x.appendChild(t);
document.body.appendChild(x);
var a= document.getElementById('bt1');
a.style.display='none';
}
var item = document.getElementById('bt2');
item.onclick = myFunction;
function myFunction() {
document.getElementsByTagName("BODY")[0].style.backgroundColor = "lime";
}
<button id= 'bt1' onclick="myFunction1();">
button 1
</button>
【问题讨论】:
-
实际上 item1 为 null,因为在您单击 button1 之前,示例中没有 #bt2 元素。因此,您不能将属性 onclick 分配给空引用。
-
我知道还有什么选择吗?
标签: javascript html css web