简体   繁体   中英

Cutting down JQuery repetitive code

In a Jquery code I've the following situation:

$("#input_field").on('input', function () {
    setTimeout(function (e) {
        $.post("endpoint.php", $('#main').serialize(), function (response) {
            parseRes(response);
        });
    }, 1);
});
$("#input_field").on("paste", function () {
    setTimeout(function (e) {
        $.post("endpoint.php", $('#main').serialize(), function (response) {
            parseRes(response);
        });
    }, 1);
});

The only different thing is the event ("input" or "paste").

Is there any way to avoid this kind of repetitions (eg. adding more events to ONE code block)?

Try,

 $("#input_field").on('input paste',function() {
     setTimeout(function(e) {
       $.post("endpoint.php", $('#main').serialize(), function (response) {
          parseRes(response);
        });
       }, 1);
  });

Please read here to know more about .on()

From the documentation :

.on( events [, selector ] [, data ], handler(eventObject) )

events: One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin".

This means your code simply boils down to:

$("#input_field").on('input paste',function() {
    // ...
});

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