javascript 在单击按钮时附加一个新的文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25910684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Appending a new textbox onclick of button
提问by Basky
Am trying to write a simplest code, like onclick of button a new textbox with unique id should be assigned and appended to the existing ones.
我正在尝试编写一个最简单的代码,例如单击按钮时,应分配一个具有唯一 ID 的新文本框并将其附加到现有文本框。
function appendRow()
{
var x = 1;
for(var i=0; i < x; i++)
{
var d = document.getElementById('div');
d.innerHTML = "<input type='text' id='tst"+ x +"'><br >";
}
++x;
}
HTML:
HTML:
<div id="div">
<button onclick ="appendRow()" value="Add Row">Add Row</button>
</div>
This might be very simple for techies.
这对于技术人员来说可能非常简单。
Thanks.
谢谢。
回答by laaposto
You are replacing the button. You have to append the new div to the already created elements. Try to use +=
instead of =
.
您正在更换按钮。您必须将新 div 附加到已创建的元素。尝试使用+=
而不是=
.
Also there is not need for a loop. You can assign unique id with just an inceasing var
也不需要循环。您可以通过不断增加的变量来分配唯一的 id
Try:
尝试:
var x=1
function appendRow()
{
var d = document.getElementById('div');
d.innerHTML += "<input type='text' id='tst"+ x++ +"'><br >";
}