我是 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/