通过使用 jQuery,如何在以下选择元素上附加一个事件,以便在索引更改时发出警报“我已更改!”?
<select id="selCars">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</select>
最佳答案
使用onchange
事件。当 selectionIndex
<select>
的元素发生变化,change
事件被触发。
在创建元素后执行这段代码。如果要添加加载,请将其包装在 $(document).ready(function(){ ... })
中,缩写为$(function(){...})
$("#selCars").change(function(){
// Do something...
//this refers to the `<select>` element
var newoption = $(this)
var selectedOption = $("option:selected", this);
//Example:
alert("I have changed!");
})
关于javascript - 如何在 <select> 元素上更改的 selectedIndex 上绑定(bind)事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7728308/