2010-09-06 21 views
7

Beim Ausführen des folgenden Codes löst der IE den Fehler aus - Objekt unterstützt diese Eigenschaft oder Methode nicht - und verweist auf die Methode cloneNode(). 'i' ist der Schleifenzähler, Quelle und Ziel sind beide HTML-Auswahlelemente.cloneNode im Internet Explorer

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

FF und Chrome verhalten sich wie erwartet. Irgendwelche Ideen, wie man IE dazu bringt, cloneNode() auszuführen? Der IE 8-Debugger zeigt source.options [i] hat eine cloneNode() -Methode.

Danke.

+2

Zeigen Sie den Code der Schleife, ich vermute, dass source.options [i] am Anfang oder Ende der Schleife kein DOM-Element ist. – BGerrissen

Antwort

8

IE erfordert die

new Option() 

Konstrukt.

document.createElement('option'); 

oder

cloneNode() 

fehl. Natürlich funktionieren alle Optionen wie erwartet in einem richtigen Webbrowser.

+8

+1 für "richtigen Webbrowser" :) – user123444555621

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

Eigentlich wirft cloneNode keinen Fehler. Brechen Sie den Code in kleinere Stücke, um richtig die Ursache des Fehlers zu identifizieren:

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! 

Oder setzen es wieder so, wie Sie es hatte, alles auf einer Linie:

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

Ah, die richtige Antwort! –

Verwandte Themen