$(document).ready(function() { // this seems fine in IE9 and 10 var $div = $("<div>"); console.log("In IE,this <div> is just fine: " + $div[0].outerHTML); // this is weird in IE var $test = $("<test>"); console.log("However,this <test> has an xml tag prepended: \n" + $test[0].outerHTML); $test.find("test"); console.log("Now,it does not: \n" + $test[0].outerHTML); console.log("Why does this behave this way?"); });
为什么会发生这种情况?它不会在Chrome或Firefox中发生.有没有更好的方法来解决这个而不是在对象上调用.find(“test”)?
编辑
解决方法
Why does this happen? It doesn’t happen in Chrome or Firefox. Is there a better way to fix this than to call .find(“test”) on the object
在未知的html元素类型上执行document.createElement时,IE会导致问题.它认为它是一个XML节点,并添加了前缀为<?XML的xml命名空间:NAMESPACE PREFIX = PUBLIC NS =“URN:COMPONENT”/> ;.相反,如果你试图让它明确提到它是一个html元素,这个问题不会发生. 尝试:
var $test = $("<html><test/></html>");
该问题不再发生.
To clarify,I’m not asking why the xml tag is added,rather,I’m wondering why the .find() call get’s rid of it. It doesn’t make sense to me.
现在,当你做一个find,jquery内部使用context.getElementsByTagName或(类似的类型,不管它是一个类还是一个标签或id等),这意味着它对元素测试执行这个操作.所以在IE中,当你这样做时,它可能在内部解决了你正在尝试对html元素执行操作而不是xml元素的事实,并且它改变了底层上下文的文档类型(但是我不知道为什么它会改变父上下文,而不仅仅是返回一个匹配).您也可以通过这个简单的例子来检查出来.
var $test = document.createElement("test"); console.log("However,this <test> has an xml tag prepended: \n" + $test.outerHTML); $test.getElementsByTagName("test"); console.log("Now,it does not: \n" + $test.outerHTML);
更新
这是documented way of defining the custom elements
The custom element type identifies a custom element interface and is a sequence of characters that must match the NCName production and contain a U+002D HYPHEN-MINUS character. The custom element type must not be one of the following values:
annotation-xml,
color-profile,
font-face,
font-face-src,
font-face-uri,
font-face-format,
font-face-name,
missing-glyph