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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...