IE8:选项标签获得“选定”属性默认情况下(和cloneNode弄乱了它) [英] IE8: The option tag gets a "selected" attribute by default (And cloneNode makes a mess of it)

查看:104
本文介绍了IE8:选项标签获得“选定”属性默认情况下(和cloneNode弄乱了它)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IE浏览器似乎在选项标签上自动添加了选定属性。

但是如果你cloneNode它,事情变得很奇怪。



<如果您在IE8中打开一个页面,请使用以下代码:

 < html> 
< body>
< form>< select>< option> o1< / option>< / select>< / form>
< script>

//没有克隆节点
var elm = document.getElementsByTagName('form')[0];
alert(elm.innerHTML);

//使用表单作为根来克隆
elm = document.getElementsByTagName('form')[0] .cloneNode(true);
alert(elm.innerHTML);

//使用select作为根来克隆
elm = document.getElementsByTagName('select')[0] .cloneNode(true)
alert(elm.innerHTML) ;

< / script>
< / body>
< / html>

您将获得:

警报,在选项标签上有一个可悲的选择属性

第二个警报,在选项标签上没有任何属性(这和其他浏览器一样!)

第三次提醒,再次出现已选中



任何想法为什么显示此属性?然后为什么cloneNode似乎随机删除它注意:你可能会想为什么这个可怜的家伙有这个问题吗?

原因是我是JS模板库的贡献者 PURE

我有一些很难找到一个干净的解决方案,以解决这个问题:-\

解决方案

选择属性的原因是补充说,它是select元素中的第一个选项元素。如果这是真的,并且没有其他选项元素已被标记为选中,则IE将选中第一个选项元素。当你像克隆节点一样克隆一个节点时,不需要将它放到dom中,它就不能被选中。如果你想要一致的结果,只需手动设置选定的属性。


IE seems to add automatically a "selected" attribute on the option tag.
But then if you cloneNode it, things get weird.

If you open a page in IE8 with the code below:

<html>
<body>
  <form><select><option>o1</option></select></form>
  <script>

      // without clone node
      var elm = document.getElementsByTagName('form')[0];
      alert(elm.innerHTML);

      // using the form as the root to clone
      elm = document.getElementsByTagName('form')[0].cloneNode(true);
      alert(elm.innerHTML);

      // using the select as the root to clone
      elm = document.getElementsByTagName('select')[0].cloneNode(true)
      alert(elm.innerHTML);

  </script>
</body>
</html>

You will get:

A 1st alert, with a miserable "selected" attribute on the option tag
A 2nd alert, with no attribute on the option tag ( This is OK, as in any other browser! )
A 3rd alert, with the "selected" appearing again

Any idea why this attribute appears?
And then why cloneNode seems to randomly remove it or not?

Note: You may think why this poor guy has a problem with this?
The reason is I'm a contributor of the JS templating library PURE
And I'm having some hard time to find a clean solution for this problem :-\

解决方案

The reason that the selected attribute is added is that it is the first option element within the select element. When this is true and no other option element is already marked as selected, IE will make the first option element selected. When you clone a node as you did without putting it in the dom, it cannot be selected. If you want consistent results, just set the selected attribute manually.

这篇关于IE8:选项标签获得“选定”属性默认情况下(和cloneNode弄乱了它)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆