2012-09-18 43 views
0

我使用phonegap删除了一个应用程序,并试图在html表格行中创建一个FOR循环。我尝试使用document.write,但页面中的所有内容都是desapears,只显示它在document.write中的内容。 我的代码是这一个:使用JavaScript和PhoneGap循环显示HTML表格

<table id="hor-minimalist-b"> 
<script language=javascript> 
for (var i=0; i<3; i++) { 
    document.write('<tr>'); 
     document.write('<td>'); 
     document.write('<input type="text" name="valor" id="valor" value="key' + i'">'); 
     document.write('</td>'); 
     document.write('</tr>'); 
} 
</script> 
</table> 

谢谢。

回答

2

这是因为您只是在页面中放置文本,您需要“创建”该元素并将它们附加到表格中。 你可以这样来做:

<table id="hor-minimalist-b"><thead></thead><tbody></tbody></table> 
<script language="javascript"> 
var table = document.getElementById('hor-minimalist-b'); // get the table element 
var tableBody = table.childNodes[1]; // get the table body 
var tableHead = table.childNodes[0]; // get the table head 
for (var i=0; i<3; i++) { 
    var row = document.createElement('tr'); // create a new row 
    var cell = document.createElement('td'); // create a new cell 
    var input = document.createElement('input'); // create a new input 
    // Set input properties 
    input.type = "text"; 
    input.id = "valor"; // It's not a good idea (to have elements with the same id..) 
    input.name = "valor"; 
    input.value = "key" + i; 
    cell.appendChild(input); // append input to the new cell 
    row.appendChild(cell); // append the new cell to the new row 
    tableBody.appendChild(row); // append the row to table body 
} 
</script> 

的insertRow()和的insertCell()可能会工作过,但我没有测试它尚未

+0

感谢您的回答。我有点新的JavaScript。我不确定我是否理解:对于我有的代码,我应该添加这个给你的代码? 另一件事,你能解释一下我是不是tableBody = table.firstChild;请?谢谢 –

+0

你应该用这个替换你的代码。 使用tbody是一种很好的做法,它会使您的代码与Internet Explorer兼容。 –

+0

它的工作原理,顺便感谢很多:),我想添加一个头。你可以编辑你使用的代码吗?我仍然想理解它。谢谢:) –