jQuery hasClass / addClass Issue
This is what I have. The li has a class of current but for some reason it's not adding the class.
if (jQuery("#sidebar li").hasClass("current")) {
jQuery(this)开发者_如何学编程.addClass("booyah");
}
this pointer is not referencing the $("#sidebar li") element.
if (jQuery("#sidebar li").hasClass("current")) {
jQuery("#sidebar li").addClass("booyah");
}
The true and easy way: jQuery("#sidebar li.current").addClass('booyah')
(If I understood your question, and you want to add 'booyah' to the li element already having 'current')
Try var'ing the side bar el first. I don't think "this" is what you think it is.
var $sideBar = jQuery("#sidebar li");
if ($sideBar.hasClass("current")) {
$sideBar.addClass("booyah");
}
Dont use this
as you are not in a context where this
represents #sidebar li
. Instead consolidate your jQuery selector to a variable and reuse the variable. This provides efficiency, as you only need to search for the element in question once, instead of twice.
var sidebarli = jQuery("#sidebar li");
if (sidebarli.hasClass("current")) {
sidebarli.addClass("booyah");
}
Here you go:
var $li = jQuery("#sidebar li");
if ($li.hasClass("current")) {
$li.addClass("booyah");
}
You can also try this: http://jsfiddle.net/shaneburgess/STZUb/
$.each(jQuery("#sidebar li"),function(){
if (jQuery(this).hasClass("current")) {
jQuery(this).removeClass("current").addClass("booyah");
}
});
精彩评论