我正在开发一个带有phonegap的Android应用程序。我正在制作一个 HTML 表,其中包含一些来自 localStorage 的 for
循环。我需要为每一行存储 for
的索引 i,以使用它从 localStorage 中检索名称类似于索引的项目。我有一些代码,但我为该效果定义的变量会被循环覆盖(当然)。代码如下:
<script language="javascript">
if(len != 0) {
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
var thead = document.createElement('th');
var row2 = document.createElement('tr'); // create a new row
var headText = document.createTextNode('Dados');
thead.scope = "col";
thead.appendChild(headText);
row2.appendChild(thead);
tableHead.appendChild(row2);
for (var i=0; i<len; i++) {
var row = document.createElement('tr'); // create a new row
var cell = document.createElement('td'); // create a new cell
var a = document.createElement('a');
var cellText = document.createTextNode(localStorage.getItem('key' + i));
var xyz = "key" + i;
a.href = "alterar.html";
a.onclick = function() { doLocalStorage(xyz) };
a.appendChild(cellText);
cell.appendChild(a); // 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>
</table>
也许我没有很好地解释自己。如果您需要更多信息,请询问。提前致谢。伊娃
最佳答案
尝试将键名放入闭包中:
function wrapper(i) {
return function() {
doLocalStorage("key" + i)
}}
a.onclick = wrapper(i);
关于javascript - 在javascript中存储for循环的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12498900/