skip to Main Content

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!

2

Answers


  1. 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'))
    });
    Login or Signup to reply.
  2. 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)
         });
    });`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search