1

I was doing some dynamic effect on DIV using JQuery when I found that
the returned value of this.id varied from function to function.

I got two sets of simple parent-child DIV tags like this:

        <DIV ID="row">
        <DIV ID="c1">              
        <Input type="radio" name="testing" id="testing" VALUE="1">testing1
        </DIV>
        </DIV> 
        <DIV ID="row">
        <DIV ID="c2">              
        <Input type="radio" name="testing" id="testing" VALUE="2">testing2
        </DIV>
        </DIV> 

Code 1.

$('#row DIV').mouseover(function(){ 
radio_btns.each(function() {
$('#row DIV).addClass('testing');  // worked
});
});


Code 2.

$('#row DIV').mouseover(function(){ 
var childDivID = this.id;
radio_btns.each(function() {
$('#'+childDivID).parent('DIV').addClass('testing');  // didn't work
});
});


I don't understand why only the first code could work
and highlighted all the "row" DIV,
but the second code failed to do so?

user327712
  • 3,291
  • 4
  • 37
  • 45
  • possible duplicate of [javascript scope problem when lambda function refers to a variable in enclosing loop](http://stackoverflow.com/questions/2828718/javascript-scope-problem-when-lambda-function-refers-to-a-variable-in-enclosing-l) – Justin Ethier May 14 '10 at 19:15
  • You mean "but the *second* code failed to do so"? – edwin May 14 '10 at 19:18
  • 1
    You can't have two elements with the same id on the same page. – edwin May 14 '10 at 19:19

2 Answers2

3

First, you have the same ID multiple times, this will lead to all sorts of odd behavior since it's invalid HTML.

Once that's corrected, for the second code example, you need an adjustment to highlight the current row on hover (note .row is now a class to eliminate the ID issue), like this:

$('.row div').mouseover(function(){
    $('#'+this.id).parent('div').addClass('testing');
});​

However, there's a better way to go about this since you already have the reference to the object, like this:

$('.row div').mouseover(function(){
    $(this).addClass('testing');
});​

Generally speaking, I can't think of a case where you'd want to use $("#"+this.id), if you have this, it should be $(this) to get the jQuery object you want.

One more item, outside the question really, if you wanted a hover in this case, use .hover() and .toggleClass(), like this:

$('.row div').hover(function(){
    $(this).toggleClass('testing');
});​
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
1

try this:

var childDivID = $(this).attr('id');
Bradley Mountford
  • 8,195
  • 4
  • 41
  • 41