I'm messing about with JavaScript/jQuery, and just trying to determine how to refactor two very similar:
$('#a-div-element').click(function() {
/* common stuff in here */
})
into one function with two arguments. I'd expected it to be somewhat similar to other languages I've used, that is:
function my_refactored_stuff(field, target_div) {
$(field).click(function{
/* common stuff in here */
});
}
But that doesn't seem to trigger when clicked
In short, if someone could do up a quick example of how to write up a function that handles common functionality across .click methods, I'd be really appreciative
Many thanks, PlankTon
Just define and re-use an event handler function.
var handler = function(event) { /* common stuff here */ }
$("#a-div-element").on("click", handler)
$("#b-div-element").on("click", handler)
var callback = function() {};
$('#a-div-element').click( callback );
Or if you wish to pass arguments:
$('#a-div-element').click(function() {
callback( /* args */ );
});
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.