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()
.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.