为什么这个 javascript 不能正确分配 .cells[] ?
为什么这不起作用?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够使用
cloneNode()
来实际克隆节点及其属性。You should be able to use
cloneNode()
to actually clone the node and its attributes.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 typedrow.cells[0] = otherRow.cells[0]
, you are saying that you wantrow.cell[0]
to reference the same DOMElement asotherRow.cells[0]
.I'm guessing you want
row.cells[0]
to have the same text or HTML asotherRow.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.