if() else() statement problem ... :/
Can someone please help me with the "if else statement", I'm having problem with this script:
$('div#wrapper div.teamwrapper:odd').addClass('odd');
$('div.teamwrapper').each(function(index){
if($('div.teamwrapper').hasClass('odd开发者_JAVA百科')){
$(this).css('top', index*35);
}else{
$(this).css('top', index*28);
}
});
My problem is that,the script above only execute the parameters inside the "if statement". It applies the parameter inside the "if statement" to all "div.teamwrapper" even if the object don't have an "odd" class. Thanks.
$('div#wrapper div.teamwrapper:odd').addClass('odd');
$('div.teamwrapper').each(function(index){
if($(this).hasClass('odd')){
$(this).css('top', index*35);
}else{
$(this).css('top', index*28);
}
});
should be
$('div#wrapper div.teamwrapper:odd').addClass('odd');
$('div.teamwrapper').each(function(index){
if($(this).hasClass('odd')){
$(this).css('top', index*35);
}else{
$(this).css('top', index*28);
}
});
Access object by this
inside function
$('div.teamwrapper').each(function(index){
if($(this).hasClass('odd')){
$(this).css('top', index*35);
}else{
$(this).css('top', index*28);
}
});
you may try this
replace $('div.teamwrapper').hasClass('odd')
with $(this).hasClass('odd')
this seems more logical than what you have written.
In this situation, the easiest would be to use the css method with a function that will set the value. You can read about it in the jQuery doc.
$('div#wrapper div.teamwrapper:odd').addClass('odd');
$('div.teamwrapper').css('top', function(index, value){
if ($(this).hasClass('odd')) {
return index*35;
} else {
return index*28;
}
});
If you really want to use the each method, do it like this:
$('div.teamwrapper').each(function(index){
var $me=$(this);
if($me.hasClass('odd')){
$me.css('top', index*35);
}else{
$me.css('top', index*28);
}
});
You should save the value of $(this)
first into a variable (like $me
), and then use that variable afterwards, this will save you a bit of resources, and a good programming practice anyways.
精彩评论