Internet Explorer中的cloneNode

Mar*_*ark 7 javascript internet-explorer clonenode

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

dest.options[dest.options.length] = source.options[i].cloneNode( true );
Run Code Online (Sandbox Code Playgroud)

FF和Chrome的行为符合预期.关于如何让IE执行cloneNode()的任何想法?IE 8调试器显示source.options [i]确实有cloneNode()方法.

谢谢.

Mar*_*ark 9

IE需要

new Option()
Run Code Online (Sandbox Code Playgroud)

构造.

document.createElement( 'option' );
Run Code Online (Sandbox Code Playgroud)

要么

cloneNode()
Run Code Online (Sandbox Code Playgroud)

将失败.当然,所有选项都可以在适当的Web浏览器中按预期工作.


gil*_*ly3 5

实际上,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!
Run Code Online (Sandbox Code Playgroud)

或者,按照你拥有它的方式把它放回原处:

dest.appendChild(source.options[i].cloneNode( true ));
Run Code Online (Sandbox Code Playgroud)