没有自动tbody与createElement / appendChild? [英] No automated tbody with createElement/appendChild?

查看:122
本文介绍了没有自动tbody与createElement / appendChild?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用javascript createElement / appendChild创建一个没有tbody的表不会在Firebug中添加tbody,但是使用innerHTML会这样做。为什么?我们应该手动添加tbody吗?

Creating a table without tbody using javascript createElement/appendChild will not add tbody in Firebug but using innerHTML will do it. Why? Should we add the tbody manually?

推荐答案

使用DOM创建方法时,必须假设您要按照您创建的方式

When using DOM creation methods, it must assume that you want the structure the way you created it.

如果要确保不同浏览器中的结构相同,那么是的,您应该始终手动添加它,即使JavaScript解析HTML也是如此。不要依赖浏览器为您插入,因为浏览器可能在这方面可能不一样。

If you want to ensure the same structure in different browsers, then yes you should always add it manually, even when JavaScript is parsing the HTML. Don't rely on the browser to insert it for you, because browsers may not behave the same in that respect.

可以在Firefox中运行的示例

它开始于这个 标记。

It starts off with this invalid markup.

<p>
    <div>original</div>
</p>

< div> 被踢出的< p> 当HTML被解析时,将其呈现为...

The <div> gets kicked out of the <p> when the HTML is parsed, leaving it rendered like this...

<p>‌</p>
<div>original</div>
<p></p>

但是,如果我们使用DOM方法创建相同的结构,Firefox不会进行任何更正。 p>

But if we create an identical structure with DOM methods, Firefox doesn't do any corrections.

var p = document.createElement('p');

p.appendChild(document.createElement('div'))
    .appendChild(document.createTextNode('new'));

document.body.appendChild(p);

所以生成的DOM现在是这样...

So the resulting DOM is now this...

<p>‌</p>
<div>original</div>
<p></p>

<p>
    <div>new</div>
</p>

所以你可以看到,即使在一个完全无效的结构的情况下,它也不会解析HTML时会看到更正。

So you can see that even in the case of a completely invalid structure, it doesn't make the corrections you'd see when it parses HTML.

最终,您应该做的不是依赖于常见的浏览器调整或更正,因为不能保证它们将成为浏览器之间相同。

Ultimately, what you should do is not rely on common browser tweaks or corrections, because there's no guarantee that they will be the same between browsers.

使用结构合理且有效的HTML,您将避免出现问题。

Use well-structured and valid HTML, and you'll avoid problems.

这篇关于没有自动tbody与createElement / appendChild?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆