2015-04-12 78 views
0

我有簡單的代碼來獲取下拉列表項的valuewrite它在文檔中。的Javascript,selectedIndex屬性返回[對象HTMLSelectElement] +值

Select a fruit and click the button: 
<select id="mySelect"> 
    <option>Apple</option> 
    <option>Orange</option> 
    <option>Pineapple</option> 
    <option>Banana</option> 
</select> 

<button type="button" onclick="myFunction()">Display index</button> 

<script> 
function myFunction() { 
    var x = document.getElementById("mySelect"); 
    x += x.options[x.selectedIndex].value; 
    document.write("<br/>" + x); 
} 
</script> 

在這裏,我面臨兩個問題,一個是,結果[object HTMLSelectElement]+value。爲什麼是它發生?

其次是document.write屬性刪除所有的身體元素,只顯示其結果。爲什麼發生?你能詳細解釋一下嗎?

+2

我建議你做一些關於JavaScript的基礎知識的研究。 – NewToJS

+1

如果你想詳細說明你想在這裏實現什麼,那將會很有幫助。至於document.write,你可以把它看作是扔掉你的書面文件,並在新的紙上寫下你的新想法。它總是這樣做。 https://developer.mozilla.org/en-US/docs/Web/API/Document/write –

回答

1
var x = document.getElementById("mySelect"); 
    x += x.options[x.selectedIndex].value; 
    document.write("<br/>" + x); 

要追加價值x這實際上是HTMLSelectElement類型的節點。

相反,它應該是:

var x = document.getElementById("mySelect"), 
    selectedValue = x.value; 
    document.write("<br/>" + selectedValue); 

您甚至不需要使用selectedIndex等,如果你只是用document.getElementById("mySelect").value它會給所選值。

關於document.write,我建議你參考MDN docs

相反文件撰寫的,您必須正餐appendChildinnerHTML

function myFunction() { 
 
var x = document.getElementById("mySelect"), 
 
selectedValue = x.value; 
 
document.querySelector("#result").innerHTML = selectedValue; 
 
}
<select id="mySelect"> 
 
    <option>Apple</option> 
 
    <option>Orange</option> 
 
    <option>Pineapple</option> 
 
    <option>Banana</option> 
 
</select> 
 
<div id="result"></div> 
 
<button type="button" onclick="myFunction()">Display index</button>

1

您是通過使用+跡象如下附加內容:

var x = document.getElementById("mySelect"); 
x += x.options[x.selectedIndex].value; 
document.write("<br/>" + x); 

所以去除+標誌,它應該給你選擇的指標,如:

var x = document.getElementById("mySelect"); 
var selectedValue = x.options[x.selectedIndex].value; 
document.write("<br/>" + x); 

秒ondly,你正在使用document.write(),你的字符串寫入整個文件刪除你的內容,所以試下你的內容寫一些DIV,如:

var x = document.getElementById("mySelect"); 
var selectedValue = x.options[x.selectedIndex].value; 
document.getElementById("some_div").innerHTML = selectedValue; 

其中「some_div」是div標籤的id其中你可以在你的HTML內容

+0

我試過你的代碼,但它只是返回'[object HTMLSelectElement]'。 – CoDINGinDARK

+0

@JokerSpirit有一個錯字,它工作正常..看到:http://jsfiddle.net/653knkon/ –

1

添加您的第一個問題,你正在使用的ID「myselect」的DOM元素在這裏設置x它:

var x = document.getElementById("mySelect"); 

然後在這一行中,x.options[x.selectedIndex].value評估爲一個字符串。通過執行+ =,您將該字符串附加/附加到x中包含的值。在自動追加前,Javascript會自動將x的值轉換爲字符串,因此您可以得到[object HTMLSelectElement]+value的結果。

x += x.options[x.selectedIndex].value; 

基本上你正在做x = [object HTMLSelectElement] + x.options[x.selectedIndex].value如果這使得它更清楚發生了什麼。

對於第二個問題,document.write(value)value替換文檔中的任何內容。欲瞭解更多信息,你可以看看這裏的文檔:https://developer.mozilla.org/en-US/docs/Web/API/Document/write

+0

當我打我的時候,哎呦沒有看到其他答案。 –