简体   繁体   中英

How to better handle events

If I have multiple events on an element I am currently handling those events as written here:

$("body").on("click", ".element", function(e) {
    // Do something on click
});

$("body").on("change", ".element", function(e) {
    // Do something on change
});

Is there a way to combine all the events on an element in one on() call? What is the best practice if there are multiple events associated with one element?

$("body").on("change click", ".element", function(e) {
    // Can I detect here if it was change or click event and perform an action accordingly?
});

You can use the type property of the event to determine which logic to execute:

$('body').on('change click', '.element', function(e) {
    if (e.type == 'click') {
        // do something...
    } 
    else if (e.type == 'change') {  
        // do something else...
    }
});

Alternatively you can provide an object to on which contains the functions to bind with the event type names as the keys:

$('body').on({
    click: function() {
        // do something on click...
    },
    change: function() {
        // do something on change...
    }
}, '.element');

Personally I would use the latter method. The whole point of having a unified on() handler is negated when using a rather ugly if statement to split the event types.

Yes! jQuery passes the event object which contain the event information:

$("body").on("change click", ".element", function(e) {
    console.log(e.type);
});

You can use the event.type . Some will say it's bad practice and others may find it useful.

$("body").on("change click", ".element", function(event) {
    switch (event.type) {
        case 'click':

        break;
        case 'change':

        break;
        default:
    }
});

jQuery event.type

 $('#element').on('keyup keypress blur change', function(event) { alert(event.type); // keyup OR keypress OR blur OR change }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" id="element" /> 

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