2015-04-04 120 views
2

我在HTML文件中的下列選擇元素:添加選項的HTML選擇元素

<select id="usr-slct"> 
</select> 

到我想只是文檔的結束之前添加使用的腳本標記的JavaScript的一些選項身體。就像這樣:

var selector = document.getElementById("usr-slct"); 
var newoption = document.createElement("option").text="User1"; 
selector.add(newoption); 

我想知道爲什麼這個代碼不會使我的網頁顯示在選擇新的選項,我怎麼能作出預期的工作?

回答

0

document.createElement("option").text="User1"返回"User1",作業的結果,而不是HTMLOptionElement。你應該代碼:

var newoption = document.createElement("option"); 
newoption.text = "User1"; 
selector.add(newoption); 

編輯:OP使用.add()方法添加optionselect元素。 HTMLSelectElement object does have .add() method.

+0

謝謝!你的答案解決了我的問題。 – Valence 2015-04-04 18:24:44

+0

@VicenteValencia非常歡迎您! – undefined 2015-04-04 18:30:28

1

您的select元素有一個'options'屬性,它是一個數組。您可以通過創建新的選項:

selector.options[selector.options.length] = new Option('text1', 'value1');

這將增加一個新的選項,與text1文字和value1價值,選擇的選項數組的結尾,這將返回你正在尋找的結果。

0

這裏的問題是,你這樣做:

var newoption = document.createElement("option").text = "User1"; 

這是不對的兩倍:

  • 首先,在Javascript中,分配返回分配的值,所以將"User1"賦值給新創建的選項的text屬性會導致變量保留字符串"User1"而不是元素;您必須首先創建該元素,然後更改其文本。其次,您應該更改textContent屬性,而不是text屬性,這對DOM不具有任何意義。

下面是正確的代碼:

var selector = document.getElementById("usr-slct"); 
var newoption = document.createElement("option"); 

newoption.textContent = "User1"; 
selector.add(newoption);