2015-04-12 77 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

当我打我的时候,哎呦没有看到其他答案。 –