简体   繁体   中英

jQuery :: How to execute one function based off two possible events

I'm looking for a clean way to fire one function that may be triggered by two possible events. For example:

$('form').on('submit', function() {
    stuff in here...
});

$('input').on('change', function() {
    same stuff in here as before...
});

I could do

function doStuff() {
    Stuff in here....
}

$('form').on('submit', function() {
    doStuff();
});

$('input').on('change', function() {
    doStuff();
});

But I was wondering if there was a more elegant way of doing this?

function doStuff() {
    Stuff in here....
}

$('form').on('submit', doStuff);

$('input').on('change', doStuff);
$(function() {

    $('form').submit(function(event) {
        event.preventDefault();
        stuff('aaa');
        $(this).unbind().submit();
    });

    $('input').change(function() {
        stuff('aaa');
    });
});

function stuff(param){
    // Some Processing!
    return(param);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM