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

前端之家收集整理的这篇文章主要介绍了javascript – 为什么使用自定义标签创建元素会在IE9或10中的outerHTML中添加xml命名空间,直到.find()方法被调用为止?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个jsfiddle演示的问题:

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

  1. $(document).ready(function() {
  2.  
  3. // this seems fine in IE9 and 10
  4. var $div = $("<div>");
  5. console.log("In IE,this <div> is just fine: " + $div[0].outerHTML);
  6.  
  7. // this is weird in IE
  8. var $test = $("<test>");
  9. console.log("However,this <test> has an xml tag prepended: \n"
  10. + $test[0].outerHTML);
  11. $test.find("test");
  12. console.log("Now,it does not: \n" + $test[0].outerHTML);
  13. console.log("Why does this behave this way?");
  14. });

为什么会发生这种情况?它不会在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元素,这个问题不会发生. 尝试:

  1. 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元素的事实,并且它改变了底层上下文的文档类型(但是我不知道为什么它会改变父上下文,而不仅仅是返回一个匹配).您也可以通过这个简单的例子来检查出来.

  1. var $test = document.createElement("test");
  2. console.log("However,this <test> has an xml tag prepended: \n"
  3. + $test.outerHTML);
  4. $test.getElementsByTagName("test");
  5. 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

猜你在找的JavaScript相关文章