2010-09-06 47 views
7

Trong khi thực hiện đoạn mã sau, IE sẽ ném lỗi - Đối tượng không hỗ trợ thuộc tính hoặc phương thức này - tham chiếu đến phương thức cloneNode(). 'i' là bộ đếm vòng lặp, nguồn và đích là cả hai phần tử chọn HTML.cloneNode trong internet explorer

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

FF và Chrome hoạt động như mong đợi. Bất kỳ ý tưởng về cách để có được IE để thực thi cloneNode()? Trình gỡ rối IE 8 hiển thị source.options [i] không có phương thức cloneNode().

Cảm ơn.

+2

Hiển thị mã vòng lặp, tôi nghi ngờ source.options [i] ở đầu hoặc cuối vòng lặp không phải là Phần tử DOM. – BGerrissen

Trả lời

8

IE đòi hỏi phải xây dựng

new Option() 

.

document.createElement('option'); 

hoặc

cloneNode() 

sẽ thất bại. Tất nhiên, tất cả các tùy chọn hoạt động như mong đợi trong một trình duyệt web thích hợp.

+8

+1 cho "trình duyệt web thích hợp" :) – 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

Thực tế, bản saoNode không phát sinh bất kỳ lỗi nào. Phá vỡ mã của bạn thành những phần nhỏ hơn để xác định đúng nguồn gốc của lỗi:

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! 

Hoặc, đưa nó trở lại theo cách bạn đã có nó, tất cả trên cùng một dòng:

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

Ah, câu trả lời đúng! –