我有一个演示问题的 jsfiddle:
$(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")
更好的方法来解决这个问题?
编辑
澄清一下,我不是在问为什么要添加 xml 标记,而是想知道为什么 .find() 调用会去掉它。这对我来说没有意义。
最佳答案
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
这是 IE 在执行 document.createElement
时导致问题的原因在未知的 html 元素类型上。它认为它是一个 XML 节点并添加前缀为 <?XML:NAMESPACE PREFIX = PUBLIC NS = "URN:COMPONENT" />
的 xml 命名空间.相反,如果您尝试明确提及它是一个 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.
现在,当您进行查找时,jquery 内部使用 context.getElementsByTagName
或(基于类、标签或 ID 等类型的相似性)这意味着它对元素 test
执行此操作.所以在 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
所以根据这个,你的标签名称是 somename-test
例如:- custom-test
IE 识别它并且它按预期工作。
关于javascript - 为什么使用自定义标签创建元素会在 IE9 或 10 的 outerHTML 中添加 xml 命名空间,直到调用 .find() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20010940/