Home > Software design >  One instance for one callback Javascript
One instance for one callback Javascript

Time:08-03

I have this code

function test(param){
    console.log(param);
}

$('div').each(function(){
     div_id = $(this).attr('id')
     $(this).on('mousemove', function(){
          test(div_id)
     });
});

But in my console.log, I have always the last value (the id of my last div).

How is it possible to have "one instance" of my callback function at each time?

Thank you!

CodePudding user response:

You can just add the eventhandler for multiple elements at once. Like so:

function test(param){
    console.log(param);
}

$('div').on('mousemove', function(){
    test($(this).attr('id'))
});

CodePudding user response:

you need make local variable to save data not globaly. So you can reinit data of div ID

`
function test(param){
    console.log(param);
}

$('div').each(function(){
 add here --> **var** div_id = $(this).attr('id')
     $(this).on('mousemove', function(){
          test(div_id)
     });
});`
  • Related