如何用与 Internet Explorer 兼容的表格替换子 DOM 元素?
我试图弄清楚如何修改 DOM 以用表替换元素。下面的代码显示了我遇到的一个问题:如果我尝试用一个简单的段落替换一个元素,它工作正常,但如果我尝试使用表格,则 Internet Explorer 8 中不会显示任何内容,尽管其他浏览器仍然可以工作。如何重写代码以使其适用于所有浏览器?
HTML:
<p>
<a onclick="replaceElementTest(this);">Replace this text</a>
</p>
<p>
<a onclick="replaceWithTableTest(this);">Replace with test table</a>
</p>
JavaScript:
// Works in all browsers
function replaceElementTest(domElement){
var p = document.createElement("p");
p.innerHTML = "This element got REPLACED!";
domElement.parentNode.replaceChild(p,domElement);
}
// Doesn't work in IE8
function replaceWithTableTest(domElement){
var table, tr, td;
table = document.createElement("table");
tr = document.createElement("tr");
td = document.createElement("td");
td.innerHTML = "This element got replaced by a TABLE!"
table.appendChild(tr);
tr.appendChild(td);
domElement.parentNode.replaceChild(table,domElement);
}
I'm trying to figure out how to modify the DOM to replace an element with a table. The following code shows a snafu I ran into: if I try to replace an element with a simple paragraph it works fine, but if I try to use a table then nothing shows up in Internet Explorer 8, although other browsers still work. How can I rewrite the code to make it work across all browsers?
HTML:
<p>
<a onclick="replaceElementTest(this);">Replace this text</a>
</p>
<p>
<a onclick="replaceWithTableTest(this);">Replace with test table</a>
</p>
JavaScript:
// Works in all browsers
function replaceElementTest(domElement){
var p = document.createElement("p");
p.innerHTML = "This element got REPLACED!";
domElement.parentNode.replaceChild(p,domElement);
}
// Doesn't work in IE8
function replaceWithTableTest(domElement){
var table, tr, td;
table = document.createElement("table");
tr = document.createElement("tr");
td = document.createElement("td");
td.innerHTML = "This element got replaced by a TABLE!"
table.appendChild(tr);
tr.appendChild(td);
domElement.parentNode.replaceChild(table,domElement);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Internet Explorer 在表格方面存在一些问题。表中使用的大多数元素实际上是只读的,这可能会导致您看到的一些问题。在我从事的一个项目中,我最终用 CSS 表替换了所有表以解决该限制。
http://support.microsoft.com/kb/239832
一些文档提到使用“表对象模型”来进行操作。
http://msdn.microsoft.com/en-us/库/ms532998(VS.85).aspx
Internet Explorer has some issues with Tables. Most of the elements used in a table are actually read-only and that might be causing some of the issues you're seeing. In a project I worked on I ended up replacing all of my tables with CSS tables to get around the limitation.
http://support.microsoft.com/kb/239832
Some docs refer to using the "Table Object Model" to do manipulation.
http://msdn.microsoft.com/en-us/library/ms532998(VS.85).aspx
感谢 Erik Noren 分享此链接:
修改后的 JavaScript 代码可在 IE8 中运行:
Thanks to Erik Noren for sharing this link:
This revised JavaScript code works in IE8: