Is there a more elegant way to apply css to "all elements but this one"?
I have some html/jQuery that I am using to implement some tabbed navigation. When a new tab is selected I need to make it's css class "active" and change the previous tabs 开发者_运维百科css class to "inactive". To do this I have been using the following code inside of my click
event:
$("ul.tabs li").removeClass("active"); //Remove any "active" class
$("ul.tabs li").addClass("inactive"); //Set all to "inactive"
$(this).removeClass("inactive"); //remove "inactive" from the item that was clicked
$(this).addClass("active"); //Add "active" class to the item that was clicked.
This works but I'm curious if anyone has found a cleaner/more elegant way of doing this?
$("ul.tabs li").click(function(){
$(".active").removeClass("active").addClass("inactive");
$(this).removeClass("inactive").addClass("active");
});
Working example at: http://jsfiddle.net/4uMmc/
Why don't you just have the inactive
style be the default style? Then, you can just do this:
$("ul.tabs li").removeClass("active");
$(this).addClass("active");
$(this).removeClass("inactive").addClass("active").siblings().removeClass("active").addClass("inactive");
Note, that it's better not to use $('ul.tabs li')
in element's click
event, so if you'd have many .tabs
only the one where the clicked element is would be affected.
However, it's better to write CSS so you won't have to use inactive
class, like this:
ul.tabs li {…} /* Inactive state */
ul.tabs li.active {…} /* Active state */
Why not simply find elements with that class and then remove it? You could simplify that down to two lines:
$('.active').removeClass('active').addClass('inactive');
$(this).addClass('active').removeClass('inactive');
This at least only evaluates the selectors once.
$("ul.tabs li").removeClass("active").addClass("inactive");
$(this).removeClass("inactive").addClass("active");
I agree with other suggestions, it's better to just get rid of the inactive class. Make the default formatting for the tab be "inactive". Then, just add/remove the active class as needed. Put the CSS for the "active" class after the default CSS for the tabs and it will supercede the default state. Then, your code could just be this:
$("ul.tabs li.active").removeClass("active");
$(this).addClass("active");
Using :not()
is way faster than .not()
Also instead of adding and removing classes use jQuery toggleClass()
You should write the code just like this:
$("ul.tabs li:not(" + $(this) + ")").toggleClass("active", "inactive");
$(this).addClass('active');
精彩评论