Javascript 动态行列

标签 javascript

我是 JavaScript 的新手。我有一个目录,我想使用 window.onresize 根据用户的窗口大小重新排列它的行和列。

window.onresize = function () {

    var w = window.innerWidth;
    var nocolumn = Math.floor(w / 252);
    if (nocolumn == 0) {
        nocolumn = 1;
    }

    var table = document.getElementById("MainContent_DataList1");
    var tbody = table.getElementsByTagName("tbody")[0];
    var link = tbody.getElementsByTagName("a");

    var norow = Math.ceil(link.length / nocolumn);
    tbody.innerHTML = "";

    console.log(norow + " " + link.length + " " + nocolumn);
    for (var i = 0; i < norow; i++) {
        var row = document.createElement("tr");
        tbody.appendChild(row);
        for (var j = 0; j < nocolumn; j++) {
            var cell = document.createElement("td");
            row.appendChild(cell);
            if ((i * nocolumn + j) < link.length) {
                cell.appendChild(link[i * nocolumn + j]);
            }
        }
    }
};

我不明白为什么变量“link”数组在我使用 innerHTML = ""; 后变为空,但我在它被清除之前存储了它。是我哪里做错了还是有其他方法可以做到这一点?

最佳答案

当您删除 innerHTML 时,您会删除 DOM 对象,因此对它们的每个引用都将指向 null。

解决它的方法是克隆这些对象:

function clone(obj) {
    if (null == obj || "object" != typeof obj) return obj;
    var copy = {};
    for (var attr in obj) {
        if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
    }
    return copy;
}

window.onresize = function () {

    var w = window.innerWidth;
    var nocolumn = Math.floor(w / 252);
    if (nocolumn == 0) {
        nocolumn = 1;
    }

    var table = document.getElementById("MainContent_DataList1");
    var tbody = table.getElementsByTagName("tbody")[0];
    var tmp = tbody.getElementsByTagName("a");
    var link = clone(tmp);

    var norow = Math.ceil(link.length / nocolumn);
    tbody.innerHTML = "";

    ...
}

感谢 clone() 方法:https://stackoverflow.com/a/728694/1057429

关于Javascript 动态行列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17139591/

相关文章:

javascript - 如何在不刷新页面的情况下从数据库刷新列表

javascript - 使用 Gmaps.js 将 Google Map 置于引导模式中

javascript - 无法将 javascript 时间戳字符串格式化为LocaleString

javascript - Safari 中的无效日期

javascript - 全日历高度且无滚动条

javascript - 如何将 HTML 作为字符串传递到 TextArea

javascript - 如何使用适合屏幕尺寸的渐变颜色为文本着色并在新行上继续颜色?

javascript - 使用 AutoSizer 包装 React-Beautiful-DND + React-Window 虚拟列表时遇到的设置问题

javascript - 检测并解析 Amazon Lex 调度机器人的 "2-4pm"等格式的时间范围

php - 在 wordpress 中检测主页有哪些不同的方法?