2011-01-06 23 views

Trả lời

44
document.getElementById('id').options.length = 0; 

hoặc

document.getElementById('id').innerHTML = ""; 
+1

+1 cho 'document.getElementById ('id'). Options.length = 0;' – epascarello

+0

Có, 'options.length' hoạt động tất cả các cách trở lại năm 1996 và Netscape 2! – bobince

+0

tùy chọn cũ tốt.length – FreshPro

5
var select = document.getElementById('yourSelectBox'); 

while (select.firstChild) { 
    select.removeChild(select.firstChild); 
} 
+0

Tôi nhận được một flash lạ trong IE6 khi –

0
<select id="thing"><option>fdsjl</option></select> 
<script> 
var el = document.getElementById('thing'); 
el.innerHTML = ''; 

// or this 

while (el.firstChild) { 
    el.removeChild(el.firstChild) 
} 
</script> 
+0

Trình duyệt chéo trong HTML có an toàn không? – hungryMind

+1

Yesssssssssssss –

0

của nó rất dễ dàng sử dụng JavaScript và DOM:

while (selectBox.firstChild) 
    selectBox.removeChild(selectBox.firstChild); 
+0

imageDropdownBox.options.length – akshay

+0

yes - như @hunter nói, options.length = 0 là một cách hay để bỏ đặt tất cả các tùy chọn (truy cập mảng Javascript như), và tôi đã bình chọn câu trả lời của anh ta cho điều đó. Nhưng tiếc là nó không hoạt động tốt trên tất cả các trình duyệt. Nếu bạn mong đợi các trình duyệt cũ hơn thì tôi mỏng DOM-level-1 là API tốt nhất. – Guss

0

Thiết lập length 0 có lẽ là cách tốt nhất, nhưng bạn có thể cũng làm điều này:

var mySelect = document.getElementById("select"); 
var len = mySelect.length; 
for (var i = 0; i < len; i++) { 
    mySelect.remove(0); 
} 
0

Giải pháp nhanh nhất tôi đã có thể tìm thấy là đoạn mã sau (lấy từ article này):

// Fast javascript function to clear all the options in an HTML select element 
// Provide the id of the select element 
// References to the old <select> object will become invalidated! 
// This function returns a reference to the new select object. 
function ClearOptionsFast(id) 
{ 
    var selectObj = document.getElementById(id); 
    var selectParentNode = selectObj.parentNode; 
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy 
    selectParentNode.replaceChild(newSelectObj, selectObj); 
    return newSelectObj; 
} 
Các vấn đề liên quan