当下拉列表值已从某些外部资源修改时,如何在下拉列表的 JQuery 中调用更改事件?
如果我更改下拉列表中的值,下面的代码可以很好地工作。
<select name="month" id="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
</select>
$('#month').change(function () {
var data = $(this).val();
alert(data);
});
但是当我更改下拉列表的值时,它不会调用更改事件,如下面的代码所示。
$("#month").val('Jan');
我在这里遗漏了什么吗?
最佳答案
更改事件仅在用户启动时触发,而不是在通过代码更改值时触发:
http://api.jquery.com/val/ Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.
在这些情况下,您需要使用 .trigger("change")
或等效的简写形式 .change()
手动触发事件:
$('#month').change(function() {
var data = $(this).val();
console.log(data);
});
// change the select value, and trigger the change event:
$("#month").val('Feb').trigger("change");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="month" id="month">
<option value="Jan">Jan</option>
<option value="Feb">Feb</option>
</select>
关于javascript - 当从某些外部资源修改 DDL 值时调用 DDL 的 Change 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955936/