Smu*_*ing 2 html javascript forms event-handling
每次从下拉菜单列表中选择新项目时,我都需要创建一个事件处理程序来运行我的函数。
到目前为止,我已经尝试过“onselect”、“onclick”、“onmousedown”和“onblur”,但这些似乎都不起作用。就此而言,每次有人从下拉菜单列表中选择新项目或同一项目时,需要更新的值是多少?
您需要使用onchange事件处理程序,您可以使用不同的方法来实现它。第一个是直接在你的html select标签中写入事件:
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
仅使用Javascript:
var mySelect = document.getElementById('mySelect');
mySelect.onchange = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
或者你可以使用jQuery:
$("#mySelect").change(function() {
$("#demo").html("You selected: " + this.value);
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
或者,对于jQuery,您可以使用该on函数:
$("#mySelect").on("change", function() {
$("#demo").html("You selected: " + this.value);
});Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)