JQuery: how to name click functions?

I have a script and I need to specify some of my anonymous click functions. For example, here is some code:

The document is ready:

$(function(){

$('#map').imagemap([
        {top_x: 1,top_y: 2,bottom_x: 290,bottom_y:380,callback: #id1 anonymous function},
        {top_x: 275,top_y: 2,bottom_x: 470,bottom_y:380,callback: #id2 anonymous function},
        {top_x: 460,top_y: 2,bottom_x: 701,bottom_y:380,callback: #id3 anonymous function}
    ]);

$('#id1').click(function() {
    ....
});

$('#id2').click(function() {
    ....
});

$('#id3').click(function() {
    ....
});
...
});

How do I write my callbacks so as not to duplicate the code outside document.ready? I tried to put everything in a row following callback:, but it did not work. So what do I put in place of anonymous function callbacks?

+3
source share
3 answers

It looks like you want the functions to clickuse a named function that can be called from another place in the code. If so, just define the functions outside the jQuery ready function and use them by name in the method click.

function id1Click() { 
  ...
}

...
$(function() {
  $('#id1').click(id1Click);
});
+10
source

, ,

$('#id3').click(function() {
    ....
});

$('#id3').click(myClickCallback);

function myClickCallback{
 ...
}
+2
function id1_click() { ... }
function id2_click() { ... }
function id3_click() { ... }

$(function(){

$('#map').imagemap([
        {top_x: 1,top_y: 2,bottom_x: 290,bottom_y:380,callback: id1_click },
        {top_x: 275,top_y: 2,bottom_x: 470,bottom_y:380,callback: id2_click },
        {top_x: 460,top_y: 2,bottom_x: 701,bottom_y:380,callback: id3_click }
    ]);

$('#id1').click(id1_click);
$('#id2').click(id2_click);
$('#id3').click(id3_click);
...
});
+1
source

Source: https://habr.com/ru/post/1796353/


All Articles