2010-09-06 67 views
7

執行以下代碼時IE會引發錯誤 - Object不支持此屬性或方法 - 引用cloneNode()方法。 'i'是循環計數器,源和目標都是HTML選擇元素。Internet Explorer中的cloneNode

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

FF和Chrome的行爲與預期相同。關於如何讓IE執行cloneNode()的任何想法? IE 8調試器顯示source.options [i]有一個cloneNode()方法。

謝謝。

+2

顯示循環的代碼,我懷疑source.options [i]在循環的開始或結束時不是DOM元素。 – BGerrissen 2010-09-06 21:39:17

回答

8

IE需要

new Option() 

構建體。

document.createElement('option'); 

cloneNode() 

將失敗。當然,所有選項都可以在正確的Web瀏覽器中按預期工作。

+8

+1爲「正確的網頁瀏覽器」:) – user123444555621 2010-09-11 14:00:31

0
<!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> 
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! 

或者,把它揹你有它的方式,全部在一行:

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

嗯,正確的答案! – 2011-01-31 21:20:57