javascript - 当从某些外部资源修改 DDL 值时调用 DDL 的 Change 事件

标签 javascript jquery

当下拉列表值已从某些外部资源修改时,如何在下拉列表的 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/

相关文章:

javascript - jQuery ..如何将文本附加到现有文本的末尾?

javascript - Mobile Safari 中的自定义 "swipe"事件未触发

javascript - 模式关闭后停止 jQuery 函数

javascript - 如果 MySQL 中 ID 相同,则合并两行

javascript - 使用类和构造函数将 JavaScript 对象基于另一个对象

javascript - HTML5数字时钟动画

javascript - 无法在动态创建的 anchor 标记上添加点击事件

jquery - 如何使用 jquery 将选定行中的标签加粗?

php - Select2 jQuery 与 JSON MySQL

javascript - JSON 响应与颜色数据的部分键不正确匹配