2012-03-12 59 views
0
<!DOCTYPE html> 
<html> 
    <head> 
     <title>Test</title> 
    </head> 
    <script type="text/javascript"> 
     function fire() { 
      console.log(document.body.children.length); 
      console.log(document.body.children[0].children.length); 
     } 
    </script> 
    <body onload="fire()"> 
     <div> 
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer pharetra ipsum erat. Aenean convallis laoreet massa, et gravida purus faucibus ac. <a id="test"/>Vestibulum libero justo.</p> 
     </div> 
    </body> 
</html> 

When you open the console, you'll see that the <a> is a children of <body>, <div> and <p>. WTF??为什么要<a id="test"/> breaks out of the DOM chain?

If <a> is closed with a "proper" closing tag the issue disappears and its only child of <p>.

Can someone explain this to me?

PS: Tested on Chrome stable.

+6

这是因为您无法自行关闭标签''。 HTML无效,可能无法预测。 – JJJ 2012-03-12 15:40:34

+1

在这里解释:http://stackoverflow.com/questions/97522/what-are-all-the-valid-self-closing-tags-in-xhtml-as-implemented-by-the-major-b – 2012-03-12 15:43:04

+0

会不会在使用Content-Type“application/xhtml + xml”时工作? – 2012-03-12 15:50:25

回答

8

I imagine it's because a is not a valid short tag.

+1
+0

当它与Content-Type“application/xhtml + xml”一起使用时它会工作吗? – 2012-03-12 15:48:44

+0

怀疑它,它仍然不是有效的浏览器将使用的XHTML/HTML5。你*可以*将它解析为XML,但浏览器不会这样做。 – Matthew 2012-03-12 15:50:54

3

As per the W3C recommdentations:

12.2 The A element [...] Start tag: required, End tag: required

It is invalid HTML. You need to at least close the tag directly after such as <a id="test"></a>.

Source: http://www.w3.org/TR/html401/struct/links.html

1

<a> tags需要结束标记(</a>)。

<a />是无效的,浏览器会试图找出你的意思,但不要指望一致的行为。

1

w3schools.com/tags/default.asp您可以看到自结束标签:

"area", "base", "basefont", "br", "col", "frame", "hr", "img", "input", "link", "meta", "param" 

A标签不应该是自我封闭。

+0

W3Schools? [W3Fools!](http://w3fools.com) – Gareth 2012-03-12 15:45:58

+0

不知道这是邪恶的,但对于标签结尾这样简单的事情,他们应该是相当正确的不是? – 2012-03-12 15:50:14

1

这是html5,而不是xml。只有void elements被允许有这样的表示。 另请参见8.1.2.1第6部分