tags:

views:

80

answers:

2

Hi all,

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?

+1  A: 

try this:

var childDivID = $(this).attr('id');
Bradley Mountford
+3  A: 

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
why it is .row instead of #row?Are they different in meaning in JQuery?
@kwokwai - They are, `.row` searches for elements with a `class` of row, `#row` looks for elements with an `id` of row.
Nick Craver