0

我的代码中有以下两个函数,addValueToSTorage 必须读取可编辑的表数据并将值添加到 localStorage 和填充表从 localStorage 读取值并使用更新的值填充表并使表不可编辑.

function addValueToStorage() {
    localStorage.clear();
    var table = document.getElementById('table');
    var i;
    var j;
    var rowLength = table.rows.length;
    for (i = 0; i < rowLength; i++) {
        var value=[];
        for (j = 0; j < 4; j++) {
            value.push(table.rows[i].cells[j].firstChild.data);
        }
        var val=JSON.stringify(value);
        var key = "xyz" + localStorage.length;
        localStorage.setItem(key, val);
    }
    populatetable();
}

function populatetable() {
    $('#table').empty();
    var header = "<tr><th>Select</th><th>Name</th><th>1</th><th>2</th><th>3</th></tr>";
    $('#table').append(header);
    for (var i = 0; i < localStorage.length; i++) {
        var key = localStorage.key(i);
        if (key.substring(0, 5) == "xyz") {
            var value = JSON.parse(localStorage.getItem(key));
            var xyzvalue = "<tr><td><input type=\"checkbox\" value=" + key + "></td><td><input type=\"text\"  value=" + value[0] + "></td><td><input type=\"text\"  value=" + value[1] + "</td><td><input type=\"text\"  value=" + value[2] + "</td><td><input type=\"text\"  value=" + value[3] + "</td></tr>";
            $('#table').append(xyzvalue);
        }
    }
    $('#table:input').prop("disabled", true);
}

addValueToStorage 能够从普通表格的单元格中读取数据,但是由于我的表格是可编辑的,因此我在表格中使用了文本框,并且 addValueToStorage 无法从单元格中读取数据,并且表格大小也完全扭曲并且由于文本框,溢出了包围它的 div。非常感谢任何有关提取数据和设置表格大小的帮助。提前致谢

4

1 回答 1

2

尝试改变:

for (i = 0; i < rowLength; i++) {
    var value=[];
    for (j = 0; j < 4; j++) {
        value.push(table.rows[i].cells[j].firstChild.data);
    }
    var val=JSON.stringify(value);
    var key = "xyz" + localStorage.length;
    localStorage.setItem(key, val);
}

for (i = 0; i < rowLength; i++) {
    var value=[];
    for (j = 0; j < 4; j++) {
        // getAttribute is probably what you're after here
        value.push(table.rows[i].cells[j].firstChild.getAttribute('value'));
    }
    var val=JSON.stringify(value);
    var key = "xyz" + localStorage.length;
    localStorage.setItem(key, val);
}
于 2013-08-14T15:49:16.213 回答