簡體   English   中英

在三個單獨的事件上觸發jQuery事件

[英]Trigger jQuery event on three separate events

我有以下功能:

function update_missing_info() {
    // do something
}

我想觸發此功能(1)當加載特定頁面時;(2)當一個下拉菜單被更改時;(3)當另一個下拉菜單更改時。

這是長格式:

// on page load
if ($('.billing-page').length > 0) {
    update_missing_info();
};

// on changing first dropdown
$('select[name="hd"]').change(function() {
    update_missing_info();
});

// on changing second dropdown
$('select[name="length"]').change(function() {
    update_missing_info();
});

有沒有辦法將所有這三個結合在一起,所以我可以做類似的事情:

if (any of the three conditions met) {
    update_missing_info();
}

您當然可以通過在jQuery中指定多個選擇器來組合事件。 您不能將其與第一個結合使用,因為它不是事件觸發器,而是簡單的條件調用。 最簡單的方法是:

// on page load
if ($('.billing-page').length > 0) {
    update_missing_info();
};

// on changing dropdowns
$('select[name="hd"], select[name="length"]').on('change', update_missing_info);

請注意,您不需要在事件處理程序中使用匿名函數,因為您無需執行任何操作即可接受沒有任何參數的調用另一個函數,因此您可以僅將該函數指定為事件觸發器。

您可以將兩個變更事件合並到其中,但是我不知道您是否可以將所有三個變更事件合並

$("select[name='hd'],select[name='length']").change(function() {
   update_missing_info();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM