我正在使用 javascript 克隆一行,然后重命名元素 ID 并将其中一个值递增 1。这不是我正在处理的实际代码,而是显示问题的通用示例。
- 它将所有内容附加到我的行的顶部而不是下面
- 增加一两次然后停止
我得到的输出是:
- 10022018
- 10032018
- 10032018
- 10032018
- 10032018
- 10012018
我期待的是:
- 10012018
- 10022018
- 10042018
- 10052018
- 10062018
- 10072018
<table id = "myTable">
<tr id="myRow">
<td>First cell <input type="text" id = "input" value = "10012018"></td>
</tr>
</table><br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var i;
for(i=0; i<5;i++){
var row=document.getElementById("myRow");
var cln = row.cloneNode(true);
row.id = "rows" + i;
var inpa = document.getElementById("input");
inpa.id = "input" + i;
var a = parseFloat(document.getElementById("input0").value);
inpa.value = (a + 10000);
document.getElementById("myTable").appendChild(cln);
}
}
</script>
最佳答案
编辑
Robin Zigmond 补充说 input0
是罪魁祸首,并且没有递增(已更正,但我未能解释)。
<小时/>var a = parseFloat(document.getElementById("input0").value); // Should be "input"
inpa.value = (a + (10000)); // Needs increment ...a + (10000 * i));
我的解释是指对行
的分配。
<小时/> 使用 for 循环时,利用增量变量。创建克隆时,您的引用仍然指向原始文件,并且没有使用它来增加任何内容,因此这就是它只是复制而不前进的原因。row.id = "rows" + i; /* This assigns a new #id to the original not a clone -- changed to `cln.id` */
演示
演示中评论了详细信息
<table id="xTable">
<tr id="xRow">
<td>First cell <input type="text" id="input" value="10012018"></td>
</tr>
</table><br>
<button onclick="xFunction()">Try it</button>
<script>
function xFunction() {
// In for loops declare i with let inside loop
// Start with 1 instead of 0 because you cloned the increment starting at 1000
for (let i = 1; i < 5; i++) {
var row = document.getElementById("xRow");
var cln = row.cloneNode(true);
// You are dealing with the clone not the original anymore
// Use i form increments
cln.id = "rows" + i;
// Target the clone specifically
// Use querySelector() to get #id, .class, or <tag>
var inpa = cln.querySelector("input");
// Once again var i to increment
inpa.id = "input" + i;
var a = parseFloat(document.getElementById("input").value);
// Remember i to increment but this is a little trickier
inpa.value = (a + (10000 * i));
document.getElementById("xTable").appendChild(cln);
}
}
</script>
关于JavaScript 输出未正确迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52655994/