2010-09-06 20 views
7

Mientras se ejecuta el siguiente código IE lanza el error - El objeto no admite esta propiedad o método - en referencia al método cloneNode(). 'i' es el contador de bucle, fuente y destino son ambos elementos de selección de HTML.cloneNode en Internet Explorer

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

FF y Chrome se comportan como se esperaba. ¿Alguna idea sobre cómo hacer que IE ejecute cloneNode()? El depurador IE 8 muestra que source.options [i] tiene un método cloneNode().

Gracias.

+2

Muestra el código del bucle, sospecho source.options [i] al principio o al final del bucle no es un elemento DOM. – BGerrissen

Respuesta

8

IE requiere el constructo

new Option() 

.

document.createElement('option'); 

o

cloneNode() 

se producirá un error. Por supuesto, todas las opciones funcionan como se espera en un navegador web adecuado.

+8

+1 para "navegador web adecuado" :) – 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 realidad, cloneNode no está arrojando ningún error. Romper su código en partes más pequeñas para identificar correctamente el origen del error:

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! 

O, poner de nuevo la forma en que lo tenía, todo en una línea:

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

¡Ah, la respuesta correcta! –