微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我有一个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

在未知的html元素类型上执行document.createElement时,IE会导致问题.它认为它是一个XML节点,并添加了前缀为<?XML的xml命名空间:NAMESPACE PREFIX = PUBLIC NS =“URN:COMPONENT”/&gt ;.相反,如果你试图让它明确提到它是一个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);

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 ex: – 自定义测试IE识别它,它的工作原理.

Demo

原文地址:https://www.jb51.cc/js/154914.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐