Swapping classes on click with jQuery, by using elements class
I have written this simple bit of jQuery that swaps out the containing ul's class based on which contained anchor is clicked. It's working fine, but, I know this is messy. I was wondering if someone could point out a way to do this same effect without having to 开发者_JS百科manually enter each class name. I am just a jQuery newb and am looking to learn more about it.
I imagine the there is a jQuery function I could write that wouldn't involve manually inserting every class name, but one that could just take the anchor tag's class and slap it onto the ul.
The jQuery
$("#infosplashnav a.news").click(function () {
$(this).parents("ul:eq(0)").removeClass();
$(this).parents("ul:eq(0)").addClass("news");
});
$("#infosplashnav a.communitylife").click(function () {
$(this).parents("ul:eq(0)").removeClass();
$(this).parents("ul:eq(0)").addClass("communitylife");
});
$("#infosplashnav a.youth").click(function () {
$(this).parents("ul:eq(0)").removeClass();
$(this).parents("ul:eq(0)").addClass("youth");
});
The HTML
<ul id="infosplashnav" class="news">
<li><a href="#news" class="news">News & Events</a></li>
<li><a href="#communitylife" class="communitylife">Community Life</a></li>
<li><a href="#youth" class="youth">Youth</a></li>
</ul>
$("#infosplashnav a").click(function () {
$(this).closest("ul").removeClass().addClass($(this).attr("class"));
});
You could do something like this:
classNames = ["news", "communityLife", "youth"];
$.each(classNames, function(n, className) {
$("#infosplashnav a." + className).click(function () {
$(this).parents("ul:eq(0)").removeClass();
$(this).parents("ul:eq(0)").addClass(className);
});
});
Don't forget you can use chaining as well, so
$(this).parents("ul:eq(0)").removeClass();
$(this).parents("ul:eq(0)").addClass("news");
Can become:
$(this).parents("ul:eq(0)").removeClass().addClass("news");
精彩评论