2010-09-29 47 views
2
來選擇框
<select id="selectId"> 
<option>Please select product ...</option> 
</select> 

我嘗試在Firefox和它的工作HTML - MOOTOOLS-添加選項在IE6

$('selectId').innertHTML = '<option>Test test</option>' 

,但是,也就是說,它不工作,如何通過字符串選項像添加上述選項即

+1

你確定這不是一個錯字錯誤嗎? $('selectId')。innertHTML ='' – lock 2010-09-29 04:55:18

+0

哦,我試着用innerHTML,結果一樣,也就是不行〜〜 – Chameron 2010-09-29 09:12:27

回答

3

使用Element類代替:

new Element('option', { 
    text: 'test option' 
}).inject($('selectId'));​ 

實施例:http://www.jsfiddle.net/EJH5b/

+0

+1。閱讀docs ppl :)我會爲所傳遞的對象添加'value:nnn'。你也可以傳遞一個'selected'屬性,就像你所期望的那樣 – 2010-09-29 13:38:32

0

如果您打算使用Mootools,那麼您應該真的使用Mootools方法,而不是在它和vanilla Javascript之間切換。這樣做的一個好處是,Mootools已經在爲您處理瀏覽器不一致問題。因此,如果你忽視它的方法,你將不得不自己照顧它們。

要訪問Mootools元素的屬性,可以在任何元素上使用setget方法。美元($)函數返回一個元素,因此您可以鏈接集並獲取該元素。

//returns selectId's HTML 
var foo = $('selectId').get('html'); 

//Sets the HTML of selectId to <option>Test test</option> 
$('selectId').set('html', '<option>Test test</option>'); // 

在這種情況下,您只需要使用set。

您應該意識到的一件事是,這不會爲選擇框添加選項,而是會用選項替換選擇框內的所有內容。因此,如果您想要使用此功能將多個選項添加到選擇框,則不會每次都重置HTML。有一個選擇框只有一個選項沒有多大意義,所以我會假設你試圖追加一個選項,而不是用一個選項來替換所有選項。在這種情況下,請執行以下操作:

//get the current options selectId's options 
var options = $('selectId').get('html'); 

//Add your own option onto the end 
options = options + '<option>Test test</option>'; 

//Set the HTML of selectId to whatever is stored in options 
$('selectId').set('html', options); 
+0

我已經嘗試過但是不能與ie一起工作,謝謝suggetsion – Chameron 2010-10-01 01:23:02

+0

在這種情況下,你是否嘗試過創建一個全新的選擇框,並刪除舊的select然後插入新的? – 2010-10-01 01:24:21