【发布时间】:2019-10-14 18:23:27
【问题描述】:
我对 javascripts 非常陌生,并试图创建一个动态 html 表单,其中有多个按钮,每个按钮单击映射到相应的表单输入。这是我的代码:
<html>
<head>
<title>Create Group</title>
<script src="/js/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function(){
$("#generate_form").click(function(){
var number = document.getElementById("number_of_groups").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
var i;
for (i=1;i<=number;i++){
var p = document.createElement("p");
var node = document.createTextNode("group " + i + " :");
p.appendChild(node);
container.appendChild(p);
var input = document.createElement("input");
input.type = "text";
var thisID = 'group_'+i;
input.id = thisID;
input.name=thisID;
container.appendChild(input);
var button = document.createElement("button");
button.id = "button_"+i;
button.type = "button";
container.appendChild(button);
button.onclick = function(){ document.getElementById(thisID).value = "hello world";};
var buttonLabel = document.createTextNode("Generate");
button.appendChild(buttonLabel);
container.appendChild(document.createElement("br"));
}
})
});
</script>
</head>
<body>
<h2>Create some group(s)</h2>
<br>
Create <input type="text" id="number_of_groups" name="number_of_groups" value="1"> group(s).
<button id="generate_form" type="button">GO</button>
<div id="container"/>
</body>
</html>`
因此,用户将输入要创建的组数并单击“开始”按钮,然后代码应使用用户选择的数字动态生成表单。每组表单都包括一个输入文本框和一个“生成”按钮。单击按钮时,输入文本框将显示“hello world”。但是,无论我单击哪个“生成”按钮,“hello world”都只会显示在最后一个输入文本框中。于是我把按钮的onclick函数改成了:
button.onclick = function(){ alert(thisID);};
然后我发现thisID 始终是最后一个输入文本框的 id,无论我单击哪个“生成”按钮。我猜这是因为在脚本完成之前,当“thisID”始终是其最新值时,点击事件的绑定才会发生。
有人可以帮我实现我想要的功能吗?非常感谢!
【问题讨论】:
-
每个人都不要使用
var,而是尝试使用let,看看是否能解决您的问题。 IE。let thisID = 'group_'+i; -
非常感谢!这实际上解决了问题。我去看看
let和var的区别。 -
再次感谢!这是非常有用的信息。
标签: javascript html dom