javascript - 为什么使用自定义标签创建元素会在 IE9 或 10 的 outerHTML 中添加 xml 命名空间,直到调用 .find() 方法?

标签 javascript jquery internet-explorer dom

我有一个演示问题的 jsfiddle:

http://jsfiddle.net/H6gML/8/

$(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); 

Demo

更新

这是一个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 识别它并且它按预期工作。

Demo

关于javascript - 为什么使用自定义标签创建元素会在 IE9 或 10 的 outerHTML 中添加 xml 命名空间,直到调用 .find() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20010940/

相关文章:

javascript - 您可以实例化 Element 对象并同时定义属性吗?

javascript - jquery 自动完成延迟不起作用

JavaScript 打开新窗口,但焦点应该留在旧窗口

javascript - 带 RequireJS 的 Underscore.string

javascript - 图像的混合/双文件输入

javascript - IE9 日期对象处理

javascript - 当您收到消息 "Object doesn' t support this property or method”时,您如何找出 "Object"是什么?

internet-explorer - 为什么 Internet Explorer 不支持 SVG SMIL 动画

javascript - 捆绑和缩小 - 当启用的脚本不起作用时

javascript - $.parseJSON(data, true) 抛出