为什么这个 javascript 不能正确分配 .cells[] ?

发布于 2024-12-21 18:14:25 字数 548 浏览 0 评论 0原文

为什么这不起作用?

var row = document.getElementById(currentRow);
var otherRow = document.getElementById(targetRow);
row.cells[0] = otherRow.cells[0];

这适用于

row.cells[0].innerHTML = otherRow.cells[0].innerHTML;

但是,单元格附加了一些属性,我也想将其移动而无需手动重新创建它们。

解决方案(注:我的实际实现中正在做更多工作,但这只是框架):

for (var i = 0; i < 4; i++) {
    var copyTo = row.cells[i];
    var copyFrom = otherRow.cells[i].cloneNode(true);
    copyTo.parentNode.replaceChild(copyFrom, copyTo);
}

Why doesn't this work?

var row = document.getElementById(currentRow);
var otherRow = document.getElementById(targetRow);
row.cells[0] = otherRow.cells[0];

This works with

row.cells[0].innerHTML = otherRow.cells[0].innerHTML;

However, there are attributes attached to the cell which I also want to move over without having to manually recreate them.

Solution (Note: more is being done in my actual implementation, but this is the framework):

for (var i = 0; i < 4; i++) {
    var copyTo = row.cells[i];
    var copyFrom = otherRow.cells[i].cloneNode(true);
    copyTo.parentNode.replaceChild(copyFrom, copyTo);
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

野稚 2024-12-28 18:14:25

您应该能够使用 cloneNode() 来实际克隆节点及其属性。

You should be able to use cloneNode() to actually clone the node and its attributes.

对岸观火 2024-12-28 18:14:25

cells 中的每个条目都引用一个 DOMElement。当您输入 row.cells[0] = otherRow.cells[0] 时,您是在说您希望 row.cell[0] 引用与 row.cell[0] 相同的 DOMElement代码>otherRow.cells[0]。

我猜您希望 row.cells[0] 具有与 otherRow.cells[0]; 相同的文本或 HTML,在这种情况下,第二个代码片段将这样做,因为您实际上是在修改 DOMElement,而不仅仅是更改您引用的 DOMElement。

Each entry in cells refers to a DOMElement. When you typed row.cells[0] = otherRow.cells[0], you are saying that you want row.cell[0] to reference the same DOMElement as otherRow.cells[0].

I'm guessing you want row.cells[0] to have the same text or HTML as otherRow.cells[0]; in which case, the second code snippet will do just that, since you are actually modifying the DOMElement, and not just changing which DOMElement you are referencing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文