2010-09-06 4 views
7

Lors de l'exécution du code suivant, IE renvoie l'erreur - Objet ne prend pas en charge cette propriété ou méthode - faisant référence à la méthode cloneNode(). 'i' est le compteur de boucle, source et dest sont les deux éléments de sélection HTML.cloneNode dans Internet Explorer

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

FF et Chrome se comportent comme prévu. Des idées sur la façon d'obtenir IE pour exécuter cloneNode()? Le débogueur IE 8 montre source.options [i] possède une méthode cloneNode().

Merci.

+2

Afficher le code de la boucle, je soupçonne source.options [i] au début ou à la fin de la boucle n'est pas un élément DOM. – BGerrissen

Répondre

8

IE nécessite l'

new Option() 

construction.

document.createElement('option'); 

ou

cloneNode() 

échouera. Bien sûr, toutes les options fonctionnent comme prévu dans un navigateur Web approprié.

+8

+1 pour "navigateur web" :) – 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

En fait, cloneNode ne génère aucune erreur. Cassez votre code en petits morceaux pour identifier correctement la source de l'erreur:

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! 

Ou, remettre la façon dont vous l'aviez, sur une seule ligne:

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

Ah, la bonne réponse! –