为什么当我使用 val() 设置 select 的值时 jquery change 事件没有触发? [英] Why does the jquery change event not trigger when I set the value of a select using val()?

查看:49
本文介绍了为什么当我使用 val() 设置 select 的值时 jquery change 事件没有触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当值由 val() 设置时,change() 事件处理程序中的逻辑不会运行,但当用户选择一个值时,它会运行他们的鼠标.这是为什么?

The logic in the change() event handler is not being run when the value is set by val(), but it does run when user selects a value with their mouse. Why is this?

<select id="single">
    <option>Single</option>
    <option>Single2</option>
</select>

<script>
    $(function() {
        $(":input#single").change(function() {
           /* Logic here does not execute when val() is used */
        });
    });

    $("#single").val("Single2");
</script>

推荐答案

因为 change 事件需要由用户发起的实际浏览器事件,而不是通过 javascript 代码.

Because the change event requires an actual browser event initiated by the user instead of via javascript code.

改为这样做:

$("#single").val("Single2").trigger('change');

$("#single").val("Single2").change();

这篇关于为什么当我使用 val() 设置 select 的值时 jquery change 事件没有触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆