I have the following finctions in my script and they do the same thing. How may I combine them?
$('.AddOne').live('click', function(){
$('.saveGroup').show();
});
$('#PhoneNumbersSelectms2side__sx option').dblclick(function(){
$('.saveGroup').show();
});
$('.AddAll').live('click', function(){
$('.saveGroup').show();
});
asked Aug 2, 2012 at 11:33
user1038814
9,70918 gold badges69 silver badges88 bronze badges
1 Answer 1
The click and dblclick event methods each take a callback function as their first argument. In javascript functions are variables. you create a function, and pass it to the callbacks
var showFn = function(){
$('.saveGroup').show();
};
$('.AddOne').live('click', showFn);
$('#PhoneNumbersSelectms2side__sx option').dblclick(showFn);
$('.AddAll').live('click', showFn);
You can further simplify this code by combining the live selectors like this:
$('.AddOne, .AddAll').live('click', showFn);
Finally, if you are using jquery 1.7.x you should use the new on event methods instead of live. Your new code would look like this:
var showFn = function(){
$('.saveGroup').show();
};
var $doc = $(document);
$doc.on('click', '.AddOne, .AddAll', showFn);
$doc.on('dblclick', '#PhoneNumbersSelectms2side__sx option', showFn);
answered Aug 2, 2012 at 11:35
mkoryak
58.1k64 gold badges204 silver badges262 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-js