Simplifying jQuery addClass and removeClass to show what's selected
I made a simple script that tells you what's s开发者_如何学Pythonelected using jQuery remove class and add class but it seems to be way too much coding.
Here is the fiddle: http://jsfiddle.net/Wz7Dv/
and here is the code:
$(".panel_nav li.kset").click(function(){
$('.panel_nav li.gset,.panel_nav li.kset,.panel_nav li.rset,.panel_nav li.dset').removeClass('selected');
$(this).addClass('selected');
});
$(".panel_nav li.gset").click(function(){
$('.panel_nav li.gset,.panel_nav li.kset,.panel_nav li.rset,.panel_nav li.dset').removeClass('selected');
$(this).addClass('selected');
});
$(".panel_nav li.rset").click(function(){
$('.panel_nav li.gset,.panel_nav li.kset,.panel_nav li.rset,.panel_nav li.dset').removeClass('selected');
$(this).addClass('selected');
});
$(".panel_nav li.dset").click(function(){
$('.panel_nav li.gset,.panel_nav li.kset,.panel_nav li.rset,.panel_nav li.dset').removeClass('selected');
$(this).addClass('selected');
});
Is there a way to strip it down?
Thank you
You should not have links between ul
and its li
elements:
<ul id="panel_nav" class="panel_nav">
<li class="gset selected"><a href="#generalsettings">General Settings</a></li>
<li class="kset"><a href="#keyboardshortcuts">Keyboard Shortcuts</a></li>
<li class='rset'><a href="#regionalsettings">Regional Settings</a></li>
<li class="dset"><a href="#resetdefaults">Reset to Defaults</a></li>
</ul>
Moving the anchor inside the li requires a change in your CSS:
.selected a {color:red}
The javascript is very repetitive and can be cut down to this:
$("#panel_nav li").click(function() {
$(this).addClass('selected').siblings(".selected").removeClass('selected');
});
JSFiddle: http://jsfiddle.net/Wz7Dv/1/
$('#panel_nav a').click(function(){
$(this).addClass('selected');
$(this).siblings().removeClass('selected');
});
Here's a fiddle
You could change your removeClass
lines to -
$('*:not(this)').removeClass('selected');
Demo - http://jsfiddle.net/zzxp8/
EDIT
I think you could boil the whole thing down to this -
$("li").click(function(){
$('li').removeClass('selected');
$(this).addClass('selected');
});
http://jsfiddle.net/zzxp8/2/
Since it looks like you're doing the same thing for each list item, this will do what I think you're trying to accomplish:
$(".panel_nav li.kset,.panel_nav li.gset,.panel_nav li.rset,.panel_nav li.dset").click(function(){
$('.panel_nav li.kset.selected,.panel_nav li.gset.selected,.panel_nav li.rset.selected,.panel_nav li.dset.selected').removeClass('selected');
$(this).addClass('selected');
});
EDIT
Actually, it'd probably be the cleanest to just add a different class to the items you want to be able to select. See this example: http://jsfiddle.net/otisskavier/Wz7Dv/3/.
精彩评论