我是编程新手, 我创建了一个表格。 我想在单击添加按钮时将此元素插入表中
我已经知道如何添加标签和文本字段,并且我想知道如何在表格中添加行并插入新标签和文本字段
<SCRIPT type="text/javascript">
var x = 1;
function add(type) {
var newlabel = document.createElement("Label");
newlabel.for = "Name";
newlabel.innerHTML = "NAME: ";
var element = document.createElement("input");
element.setAttribute("type", type);
element.setAttribute("name", type);
element.setAttribute("value", "Name"+x);
element.setAttribute("id", "Name"+x);
element.setAttribute("style","width: 64");
var newlabel1 = document.createElement("Label");
newlabel1.for = "AGE";
newlabel1.innerHTML = "AGE: ";
var element1 = document.createElement("input");
element1.setAttribute("type", type);
element1.setAttribute("name", type);
element1.setAttribute("value", "AGE"+x);
element1.setAttribute("id", "AGE"+x);
element1.setAttribute("style","width: 64");
var foo = document.getElementById("fooBar");
foo.appendChild(newlabel);
foo.appendChild(element);
foo.appendChild(newlabel1);
foo.appendChild(element1);
x++;
}
</script>
<form id="fooBar" form name="form1" method="post" action="">
<table id = "mytable" table border="1">
<tr>
<th scope="col">name: </th>
<th scope="col">
<label for="name"></label>
<input type="text" name="name" id="name">
</th>
<th scope="col">age:</th>
<th scope="col">
<label for="name2"></label>
<input type="text" name="name2" id="name2">
</th>
</tr>
</table>
<INPUT type="button" value="Add" onClick="add('text')" style="width:100px;"/>
</form>
最佳答案
在您的代码中:
> <SCRIPT language="javascript">
脚本元素的语言属性已弃用,类型是必需的,使用:
<script type="text/javascript">
...
newlabel.setAttribute("for", "Name");
for 的值属性必须与表单控件的 ID 匹配,否则不会与该控件关联。此外,设置元素属性比使用 setAttribute 更容易、更稳健:
newlabel.htmlFor = "Name";
请注意,HTML for 属性被引用为 htmlFor属性,因为 for 是 javascript(实际上是 ECMAScript)中的保留字。
> newlabel.innerHTML = "NAME: ";
您可能应该附加一个文本节点,而不是使用innerHTML属性:
newlabel.appendChild(document.createTextNode("NAME: "));
您的 HTML 应如下所示:
<form id="fooBar">
<input type="button" value="Add fields" onclick="add();">
</form>
请注意,如果您使用 BUTTON元素,可能发生的情况是正在提交表单(因为默认情况下按钮元素是提交按钮),因此正在添加字段,但由于表单已提交,因此您看不到它。确保按钮是 type="button"。
关于javascript - 如何创建表格并在单击按钮时插入此标签和文本字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12310809/