我有一个
HTML表单.单击该按钮时,javascript函数会添加一个新字段.我正在尝试让该功能也为该字段添加“标签”.
我已经尝试过使用document.createElement(“LABEL”),但这不允许我更改innerHtml(或者我可能做错了..),也没有添加结束
这是我的代码.谢谢!
var instance = 2;
function newTextBox(element)
{
instance++;
// Create new input field
var newInput = document.createElement("INPUT");
newInput.id = "text" + instance;
newInput.name = "text" + instance;
newInput.type = "text";
instance++;
document.body.insertBefore(document.createElement("BR"),element);
document.body.insertBefore(newInput,element);
}
</script>
</head>
<body>
<LABEL for="text1">First name: </LABEL>
<input id="text1" type="text" name="text1">
<LABEL for="text2">Last name: </LABEL>
<input id="text2" type="text" name="text2">
<input type="button" id="btnAdd" value="New text Box" onclick="newTextBox(this);" />
</body>
解决方法
function newTextBox(element)
{
instance++;
// Create new input field
var newInput = document.createElement("INPUT");
newInput.id = "text" + instance;
newInput.name = "text" + instance;
newInput.type = "text";
var label = document.createElement("Label");
label.htmlFor = "text" + instance;
label.innerHTML="Hello";
instance++;
document.body.insertBefore(document.createElement("BR"),element);
document.body.insertBefore(newInput,element);
document.body.insertBefore(label,newInput);
注意,label标签的for属性对应于javascript中标签对象的属性htmlFor