简体   繁体   English

如何更好地处理事件

[英]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? 有没有办法在一个on()调用中组合元素上的所有事件? 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: 您可以使用事件的type属性来确定要执行的逻辑:

$('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: 或者,也可以提供一个目的是on其中包含与事件类型名称作为键结合功能:

$('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. 使用一个相当丑陋的if语句来分割事件类型时,取消了统一on()处理程序的重点。

Yes! 是! jQuery passes the event object which contain the event information: jQuery传递包含事件信息的事件对象:

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

You can use the event.type . 您可以使用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 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" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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