2013-10-08 32 views
0

我正在嘗試創建動態文本框。只有在上一個文本框非空的情況下才應該創建文本框。到目前爲止,我已經完成了這項工作如何在javascript中結合兩個變量?

<!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> 

但str未被識別爲元素ID。任何幫助將不勝感激。

+0

你想做什麼?您的頁面上沒有元素,ID爲'str',並且您不會將ID分配給您創建的任何元素。此外,你的if語句的兩個分支都在做同樣的事情。 –

+0

box是對dom元素的引用,而不是字符串。 –

+0

str ='box'+ i;更接近你想要的我猜 – GameAlchemist

回答

1
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; 
} 
+0

它不工作! – Ani

+0

現在是嗎? – GameAlchemist

+0

是的,它的工作。謝謝。好吧,我設法修復我的代碼也:) .. – Ani

0

你的冤屈:

  1. str = 'box' + i;

  2. 忘記分配box.id = str

  3. 使用getElementById(str)而不是getElementById('str')