Javascript internet explorer中的克隆节点

Javascript internet explorer中的克隆节点,javascript,internet-explorer,clonenode,Javascript,Internet Explorer,Clonenode,执行以下代码时,IE抛出错误——对象不支持此属性或方法——引用cloneNode()方法i'是循环计数器,source和dest都是HTML选择元素 dest.options[dest.options.length] = source.options[i].cloneNode( true ); FF和Chrome的行为符合预期。关于如何让IE执行cloneNode()有什么想法吗?IE 8调试器显示源代码。选项[i]确实有一个cloneNode()方法 谢谢。IE需要 new Option()

执行以下代码时,IE抛出错误——对象不支持此属性或方法——引用cloneNode()方法i'是循环计数器,source和dest都是HTML选择元素

dest.options[dest.options.length] = source.options[i].cloneNode( true );
FF和Chrome的行为符合预期。关于如何让IE执行cloneNode()有什么想法吗?IE 8调试器显示源代码。选项[i]确实有一个cloneNode()方法

谢谢。

IE需要

new Option()
构造

document.createElement( 'option' );

将失败。当然,在适当的web浏览器中,所有选项都能正常工作。


<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Untitled Document</title>
<style>
p, select,option{font-size:20px;max-width:640px}
</style>
<script>

function testSelect(n, where){
    var pa= document.getElementsByName('testselect')[0];
    if(!pa){
        pa= document.createElement('select');
        where.appendChild(pa);
        pa.name= 'testselect';
        pa.size= '1';
    }
    while(pa.options.length<n){
        var i= pa.options.length;
        var oi= document.createElement('option');
        pa.appendChild(oi);
        oi.value= 100*(i+1)+'';
        oi.text= oi.value;
    }
    pa.selectedIndex= 0;
    pa.onchange= function(e){
        e= window.event? event.srcElement: e.target;
        var val= e.options[e.selectedIndex];
        alert(val.text);
    }
    return pa;
}
window.onload= function(){
    var pa= testSelect(10, document.getElementsByTagName('h2')[0]);
    var ox= pa.options[0];
    pa.appendChild(ox.cloneNode(true))
}

</script>
</head>

<body>
<h2>Dynamic Select:</h2>
<p>You need to insert the select into the document, 
and the option into the select,
before IE grants the options any attributes.
This bit creates a select element and 10 options,
and then clones and appends the first option to the end.
<br>It works in most browsers.
</p>
</body>
</html>
无标题文件 p、 选择,选项{字体大小:20px;最大宽度:640px} 函数testSelect(n,其中){ var pa=document.getElementsByName('testselect')[0]; 如果(!pa){ pa=document.createElement('select'); 其中,儿童(pa); pa.name='testselect'; pa.size='1'; }
而(pa.options.length实际上,cloneNode并没有抛出任何错误。请将代码分解为较小的块,以正确识别错误的来源:

var origOpt = source.options[i];
var clonedOpt = origOpt.cloneNode( true );  // no error here
var destOptLength = dest.options.length;
dest.options[destOptLength] = clonedOpt;    // error!
dest.options.add(clonedOpt);                // this errors too!

dest.appendChild(clonedOpt);                // but this works!
或者,把它放回原来的样子,全部放在一行上:

dest.appendChild(source.options[i].cloneNode( true ));

我发现这篇文章很有用:

显示循环的代码,我怀疑是源代码。循环开头或结尾的选项[I]不是DOM元素。
dest.appendChild(source.options[i].cloneNode( true ));