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?
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
.rowis now a class to eliminate the ID issue), like this:However, there’s a better way to go about this since you already have the reference to the object, like this:
Generally speaking, I can’t think of a case where you’d want to use
$("#"+this.id), if you havethis, 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: