【问题标题】:Fire event after jQuery select list options have changed via another elements onchange eventjQuery 选择列表选项通过另一个元素 onchange 事件更改后的触发事件
【发布时间】:2012-02-14 20:47:27
【问题描述】:

我有一个选择列表 (#select2),每次更改另一个选择列表 (#select1) 时,它的选项都会更改。

select2 的选项始终依赖于 #select1 的值,并且每次 #select1 更改时都会更改。

是否有一个函数可以绑定到 #select2 元素,该函数会在其选项列表更改完成后触发(每次受 #select1 影响)?

我似乎无法向 select1 元素添加 onchange 处理程序来执行我想要的操作,因为它会在 select2 的选项列表完成之前触发。

【问题讨论】:

    标签: jquery onchange


    【解决方案1】:

    您可以使用trigger()bind() 方法来引发和侦听自定义事件:

    试试这个:

    $("#select1").change(function() {
        // update options in #select2
        $("#select2").trigger("updatecomplete");
    });
    
    $("#select2").bind("updatecomplete", function() {
        // this will fire when #select1 change event has finished updating the options.
    });
    

    更多信息trigger()


    更新答案 - 2016 年 9 月

    请注意,bind() 现在已弃用。你应该改用on()

    $("#select2").on("updatecomplete", function() {
        // this will fire when #select1 change event has finished updating the options.
    });
    

    【讨论】:

    • 太棒了!可以被视为“点击”事件
    【解决方案2】:

    通过 javascript 进行的更改不会触发事件。您需要在更改它的代码中自己触发它。

    $("#select2").change();
    

    【讨论】:

    • 为了清楚起见,$("#select2").change() 事件是否不会因为 select1 的 jquery 重置 select2 中的选项而触发?
    • 对,我假设您已经将处理程序绑定到select2,但此事件不会自动触发。您可以自己致电change 来触发该事件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多