首页 > selecet元素克隆为什么不能保存选中项

selecet元素克隆为什么不能保存选中项

克隆一个select元素时,希望保存当前的选择项
而克隆select元素总是保存着被克隆select的selectIndex属性初始值,为什么不能复制当前selectIndex属性呢?或者说是option元素的selected属性值呢

<select id="select">  
    <option value="1">The 1st Option</option>  
    <option value="2">The 2nd Option</option>  
    <option value="3">The 3rd Option</option>  
    <option value="4">The 4th Option</option>  
    <!-- <option value="5" select="selected">The 5th Option</option>   -->
</select>  
<script>
    var sel=document.getElementById("select");
        sel.onchange=function(){
            var sel_2=sel.cloneNode(true);
            sel.parentNode.appendChild(sel_2);
            //克隆的select元素selectIndex总是为0
            //document.getElementsByTagName("select")[1].selectedIndex
            //不设置selected:0
            //设置了selected:4
        };
</script>

研究了一下,cloneNode应该只能copy字面上的HTML,原文如下

Cloning a node copies all of its attributes and their values, including intrinsic (in–line) listeners. It does not copy event listeners added using addEventListener() or those assigned to element properties. (e.g. node.onclick = fn)

selecedIndex不是写在字面HTML上的属性,所以不能copy。

另外,关于optionselected属性,由于在页面上去选择选上时这个属性在HTML上不会跟着走,所以copy时只能拿页面最初时候的那个样子。

但是,你可以这么做,手动的去把selected属性加上去:

var option = sel.children[1];
var selected = document.createAttribute('selected');
option.attributes.setNamedItem(selected);

这样再copy时就能把selected弄上去

【热门文章】
【热门文章】