如何在javascript中组合两个变量?
我正在尝试创建动态文本框。仅当上一个文本框为非空时,才应创建文本框。到目前为止,我已经做到了这一点如何在javascript中组合两个变量?,javascript,variables,Javascript,Variables,我正在尝试创建动态文本框。仅当上一个文本框为非空时,才应创建文本框。到目前为止,我已经做到了这一点 <!DOCTYPE html> <html> <head> <script> var i=0; function myFunction() { var box = document.createElement("input"); box.type = "text"; var str=box+i; if(i==0) { document.body
<!DOCTYPE html>
<html>
<head>
<script>
var i=0;
function myFunction()
{
var box = document.createElement("input");
box.type = "text";
var str=box+i;
if(i==0)
{
document.body.appendChild(box);
}
else if(document.getElementById('str').value!=0)
{
document.body.appendChild(box);
}
i++;
}
</script>
</head>
<body>
<input type="button" id="button" onclick="myFunction()" value="Show box" />
</body>
</html>
var i=0;
函数myFunction()
{
变量框=document.createElement(“输入”);
box.type=“text”;
var-str=box+i;
如果(i==0)
{
文件.正文.附件(框);
}
else if(document.getElementById('str').value!=0)
{
文件.正文.附件(框);
}
i++;
}
但是str不被识别为元素id。任何帮助都将不胜感激。您的错误:
var i = 0;
function myFunction() {
var lastInput = document.getElementById('box' + i);
if (!lastInput) {
// always put first input
document.body.appendChild(createInput(0));
} else if (lastInput.value != 0) {
// append another one only if previous input content is non-null
i++;
document.body.appendChild(createInput(i));
}
}
function createInput(i) {
var box = document.createElement("input");
box.type = 'text';
box.id = 'box' + i;
box.value = 0;
return box;
}
str='box'+i代码>
box.id=str
getElementById(str)
而不是getElementById('str')
你想干什么?您的页面上没有ID为
str
的元素,您也没有为您创建的任何元素分配ID。另外,if语句的两个分支都在做相同的事情。box是对dom元素的引用,而不是字符串。str='box'+i;更接近你想要的我猜是的,它起作用了。非常感谢。嗯,我也设法修复了我的代码:)好的,祝你一切顺利!因此,请将我的anwswer设置为已接受,如果您的最终解决方案有显著不同,请编辑您的帖子,添加您找到的解决方案。干杯