Why is a self-closing iframe tag preventing furthe

2019-01-12 09:17发布

问题:

On Firefox and Safari, the following code displays only the first iframe

<iframe src="http://www.bing.com"/>
<iframe src="http://www.tsr.ch"/>

whereas adding the closing tag solves the issue

<iframe src="http://www.bing.com"></iframe>
<iframe src="http://www.tsr.ch"></iframe>

I don't understand why it does not work. When parsing the second example with DOMParser, it anyways does the transformation to self-closing iframes.

fiddle here : http://jsfiddle.net/hLcukz6p/

回答1:

Because the iframe element isn't a self-closing element. The versions of Firefox and Safari you're using are treating the /> at the end as just > and assuming everything after it is contained within the iframe.

If we attempt to pass the code you've given through W3C's validator we'll see the following errors:

Error: Self-closing syntax (/>) used on a non-void HTML element. Ignoring the slash and treating as a start tag.

<iframe src="http://www.bing.com"/>

Error: End of file seen when expecting text or an end tag.

</html>

Error: Unclosed element iframe.

<iframe src="http://www.bing.com"/>

If you inspect your document with your browser's Element Inspector, you'll see what's going on.

Chrome, which I'm using, converts the invalid <iframe ... /> to <iframe ...></iframe>:



回答2:

There's no such thing as a "self-closing iframe" in HTML (or, for that matter, any other kind of self-closing tag, there are just some elements where the end tag can or must be omitted and iframe is not one of them).

You have an iframe start tag with an invalid / at the end of it.

Everything that follows is a child node of the iframe, so it treated as alternative content for browsers that don't support iframes.


XHTML supports self-closing tags, and any element may be added using one (if you aren't being HTML compatible).

HTML 5 allows for a / at the end of a start tag for an element when the end tag is omitted, but it has no effect beyond satisfying XML addiction and bad syntax highlighters.



标签: html dom iframe