删除/添加链接类onclick [英] Removing/adding link class onclick
问题描述
我研究了相当多的onClick链接的更改,但不能很好地找出我需要的解决方案。我有一个侧栏菜单,包含三个链接。我有一个默认的活动类添加到我想显示为默认的内容。但是,当我单击侧边栏中的另一个链接时,我想要删除上一个链接的活动类,替换为非活动,然后将活动应用于新链接。这是我的代码:
I researched quite a bit on onClick changes for links but couldn't quite figure out the solution I need. I have a side bar menu that contains three links. I have a default "active" class added to the content I want to appear as default. However when I click another link in the sidebar, I want the previous link's "active" class to be removed, replaced with "inactive", then apply "active" to the new link. Here's my code:
HTML:
<div id="sidebar">
<ul>
<li><a href="#" id="1" class="active">1</a></li>
<li><a href="#" id="2" class="inactive">2</a></li>
<li><a href="#" id="3" class="inactive">3</a></li>
</ul>
</div>
CSS:
a.active {
background-color:#ccd9ff;
border-radius:15px 15px;
}
a.inactive {
border:0;
background:0;
}
jQuery:
$(function(){
$('a.inactive').click(function(){
$('a.inactive').removeClass('inactive');
$(this).addClass('active');
});
});
我读这个以前的帖子,这帮助我找出了如何addClass onclick(上),但是我不能删除'活动'类非活动链接。有人可以帮助我吗?
I read this previous post which helped me figure out how to addClass onclick (above), however I wasn't able to then remove the 'active' class of the inactive links. Can someone help me out?
推荐答案
您可以使用 delegate()
[docs] 方法仅在 #sidebar
的后代触发处理程序, / code>。
Event delegation would be nice here. You can use the delegate()
[docs] method to only trigger the handler on descendants of #sidebar
that have the inactive
class.
然后使用 toggleClass()
[docs] 方法切换 code>和
非活动
类。
Then use the toggleClass()
[docs] method to toggle the active
and inactive
classes.
$(function(){
var sidebar = $('#sidebar'); // cache sidebar to a variable for performance
sidebar.delegate('a.inactive','click',function(){
sidebar.find('.active').toggleClass('active inactive');
$(this).toggleClass('active inactive');
});
});
您可以在这里测试代码: http://jsfiddle.net/dstpt/
这篇关于删除/添加链接类onclick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!