为什么select仅返回第一个值?

时间:2019-05-27 11:04:12

标签: javascript select onchange

函数中有两个值。输入和选择,除选择返回第一个值(px)之外,其他所有操作均正常。我在哪里弄错了?

<input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>
function Width(){
var x = document.getElementById("width").value;
var y = document.getElementById("widthpixselpercentage").value;
        document.getElementById(someDiv).style.width = x + y;

}

2 个答案:

答案 0 :(得分:1)

如果您要使用javascript从选择框中获取值,则:

var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].value;

如果要使用javascript从选择框中输入文本,则

var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].text;

请尝试以下操作:

function Width(){
var x = document.getElementById("width").value;
var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].value;
        document.getElementById("someDiv").style.width = x + y;

}
#someDiv{
border:1px solid;
height:5px;
}
<input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>

答案 1 :(得分:0)

您可以参考以下示例代码:

function Width(vv)
{
	alert(vv.value);
}
<input id="width" onchange="Width(this)" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width(this)" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>

相关问题