2012-03-12 55 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部分