每次单击 id 为“button0”的按钮时,以下代码都会成功地将按钮添加到表单中。但是萤火虫给了我错误
form1 is null
[Break On This Error]
form1.appendChild(element);
并且新按钮将不会执行函数“foo()”,尽管它已被设置为其 onclick 值。这是代码
var counter = 0;
function add(){
counter++;
var element = document.createElement("input");
element.type = "button";
element.value = "test";
element.name = "button"+counter;
element.id = "button"+ counter;
element.onclick="foo()";
var form1 = document.getElementById("form1");
var body1 = document.getElementById("b1");
var header = document.getElementById("header");
form1.appendChild(element);
header.innerHTML = "Two Buttons";
};
function foo(){
var butt = document.getElementById("button1");
butt.value = "works";
console.log("works");
};
add();
如果我使用 document.form1.appendChild(element); 我也会得到一个萤火虫错误(未定义);
有趣的是,我每次点击都会得到新按钮。只是按钮不起作用。
这是我的html
<body id = "b1">
<script src = "button-in-code.js"></script>
<h1 id = "header">Buttons</h1>
<form id = "form1" name = "form1">
<input type="button" id = "button0" name="sel" value="Select all" onclick="add()">
</form>
<hr>
<address></address>
<!-- hhmts start -->Last modified: Mon Jul 8 10:07:26 EDT 2013 <!-- hhmts end -->
</body> </html>