Danin Na
Danin Na

Reputation: 409

optimize .click( some function ) jquery code

I have many function

//function 1
alert('error_1');

//function 2
alert('error_2');

And so on

i need functions run , when I click on buttons . For example

$('.button_1').click(function() {

     //function 1
     alert('error_1');
     //function 2
     alert('error_2');
     //And so on ...

});

$('.button_2').click(function() {

     //function 1
     alert('error_1');
     //function 2
     alert('error_2');
     //And so on ...

});

$('.button_3').click(function() {

     //function 1
     alert('error_1');
     //function 2
     alert('error_2');
     //And so on ...

});
// And so on

but I need optimize this code , For example

var function_1 = function() {alert('error_1');}
var function_2 = function() {alert('error_2');}
var function_3 = function() {alert('error_3');}
// And so on

$('.button_1').click( function_1 , function_2 , function_3)
$('.button_2').click( function_1 , function_2 , function_3)
$('.button_3').click( function_1 , function_2 , function_3)
// And so on

but .click( function_1 , function_2 , function_3) doesn't work

So what would u guys suggest me to do ?

Upvotes: 0

Views: 83

Answers (3)

Ricardo Pontual
Ricardo Pontual

Reputation: 3757

You can use eval:

$('.button_1').click(function () {
eval('function_1')();eval('function_2')();eval('function_3')()})

Upvotes: -1

PeterKA
PeterKA

Reputation: 24638

Once you define the functions, function_1, function_2, function_3, .... and you give all your buttons a common class, say .button, use this:

$('.button').click( function() {
    function_1();
    function_2();
    function_3();
    ....
});

Upvotes: 1

epascarello
epascarello

Reputation: 207501

Make a function that calls all the methods and bind to it.

var function_1 = function() {alert('error_1');}
var function_2 = function() {alert('error_2');}
var function_3 = function() {alert('error_3');}
// And so on

$('.button_1, .button_2, .button_3').on("click", function() { 
    function_1();
    function_2();
    function_3();
});

And you can simplify the '.button_1, .button_2, .button_3' by giving them all a common class.

Upvotes: 2

Related Questions