0

I have a javascript code as follow:

$( "#hover0" )
    .mouseenter(function() {
        $( "#hover0" ).attr("style","background-color:#e1e8ed;");
    })
    .mouseleave(function() {
        $( "#hover0" ).removeAttr();
    });

which works perfectly but as soon as I change it to the following it does not work:

var item=0;
$( "#hover"+item )
    .mouseenter(function() {
        $( "#hover"+item  ).attr("style","background-color:#e1e8ed;");
    })
    .mouseleave(function() {
        $( "#hover"+item  ).removeAttr();
    });

what is the problem?Can anyone help me how I can do it like the second approach?(Actually the real scenario is a for loop with item changing as each loop passes)

Update:

Here is my loop:

for (var item in jsresult) {

    if (jsresult[item] != "null") {

    $('#tweetWrapper')
        .append("<div class='tweetCon' id='hover"+item+"' >" +
                "<div class='tweetimgcon' ><img alt='' height='50px' src='"+jsresult[item].url+"'></div>" +
                "<div class='tweetcontitle' >"+jsresult[item].name+"</div>" +
                "<div class='tweetcondate' >"+jsresult[item].date+"</div>" +
                "<div class='tweetconcontent' '>"+jsresult[item].text+"</div>" +
                "</div><div class='ttest' style='float:left;height:300px;width:100%;display:none;'></div>");

    $("#hover0")
      .mouseenter(function() {
        $( "#hover0" ).attr("style","background-color:#e1e8ed;");
      })
      .mouseleave(function() {
        $( "#hover0" ).removeAttr();
      });
    }
}
GillesC
  • 10,647
  • 3
  • 40
  • 55
HMdeveloper
  • 2,772
  • 9
  • 45
  • 74

1 Answers1

4

Those handlers will always use the last-known value of item, not the value that it had when you set them up.

Better to move the handler code into a setup function, and call that - its local variable will always have the right value.

function addHandlers(item) {
  $( "#hover"+item )
    .mouseenter(function() {
      $( "#hover"+item  ).attr("style","background-color:#e1e8ed;");
    })
    .mouseleave(function() {
      $( "#hover"+item  ).removeAttr('style');
    });
}

// called as...
//
for(var item in jsresult)
{     
  if (jsresult[item]!="null")
  {
    // wrappers, etc., then...
    //

    addHandlers( item );
  }
}
Paul Roub
  • 36,322
  • 27
  • 84
  • 93