每次从下拉菜单列表中选择新项目时,我都需要创建一个事件处理程序来运行我的函数。
到目前为止,我已经尝试了#34; onselect"," onclick"," onmousedown"," onblur"这些似乎都不起作用。每次有人从下拉菜单列表或同一项目中选择新项目时更新所需的值是什么?
答案 0 :(得分:2)
您需要使用onchange
事件处理程序,您可以使用不同的方法实现此操作。第一个是直接在 html select
标记中撰写活动:
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}

<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
&#13;
仅使用 Javascript :
var mySelect = document.getElementById('mySelect');
mySelect.onchange = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
&#13;
<p>Select a new car from the list.</p>
<select id="mySelect">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
&#13;
或者您可以使用 jQuery :
$("#mySelect").change(function() {
$("#demo").html("You selected: " + this.value);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select a new car from the list.</p>
<select id="mySelect">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
&#13;
jQuery 的替代方案,您可以使用on
函数:
$("#mySelect").on("change", function() {
$("#demo").html("You selected: " + this.value);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Select a new car from the list.</p>
<select id="mySelect">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>
<p id="demo"></p>
&#13;
答案 1 :(得分:0)
尝试使用onchange事件处理程序。每次选择更改时都会调用该方法。Check this
答案 2 :(得分:0)
您正在谈论下拉菜单列表,可以使用各种html元素创建,如果您使用'select',那么您必须使用onchange事件,但如果您使用的是无序列表或其他内容必须使用onclick作为列表项
答案 3 :(得分:0)
您需要在更改时使用,原因是您要更改输入表单元素的值:Check This example