javascript - 我需要为 JavaScript 中的下拉菜单列表使用什么事件处理程序?

标签 javascript html 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;
}
<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>


仅使用 Javascript:

var mySelect = document.getElementById('mySelect');

mySelect.onchange = function() {
   var x = document.getElementById("mySelect").value;
   document.getElementById("demo").innerHTML = "You selected: " + x;
 }
<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>


或者你可以使用jQuery:

$("#mySelect").change(function() {
    $("#demo").html("You selected: " + this.value);
  });
<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>

或者对于 jQuery,您可以使用 on功能:

$("#mySelect").on("change", function() {
    $("#demo").html("You selected: " + this.value);
  });
<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>

关于javascript - 我需要为 JavaScript 中的下拉菜单列表使用什么事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33932395/

相关文章:

javascript - 用jquery获取数组的值

javascript - ember-data 悲惨错误重复记录

javascript - 如何在可拖动div上应用悬停效果

javascript - 无法在移动 View 中显示导航栏

javascript - React 中的数据管理策略

ruby - webrat 自动填充表单字段

java - 从网页发送数据到java套接字服务器的最快方法

javascript - 用于水平滚动到下一个 div jQuery 的简单上一个和下一个按钮

jquery - 使用 CSS3 的可扩展菜单项

javascript - 动态创建输入元素时设置输入元素的 ID