刚刚开始接触 jQuery 的优点,我要解决的第一个任务是在链接被点击后加下划线。自然,在单击同一 div 中的不同链接后,前一个链接不再带下划线...
问候
刚刚开始接触 jQuery 的优点,我要解决的第一个任务是在链接被点击后加下划线。自然,在单击同一 div 中的不同链接后,前一个链接不再带下划线...
问候
所以基本上,你想要一种导航菜单,一旦点击就会改变链接的样式。首先,制作一个仅强调以下内容的样式:
<style type="text/css">
a.currentlyActive
{
text-decoration: underline;
}
</style>
您将要修改的代码是...
<a class="navigation" href="#">My First Link</a>
<a class="navigation" href="#">My Second Link</a>
<a class="navigation" href="#">My Third Link</a>
只是一些带有某种类型的类的链接,表示它是你想要下划线而不是下划线的链接。
接下来,添加一点 jQuery 魔法以在单击时应用样式。同时,您将希望从所有其他样式中删除该样式。
<script type="text/javascript">
$(function() {
$('.navigation').click(function() {
// this removes the underline class from all other ".navigation" links.
$('.navigation').removeClass('currentlyActive');
// this makes the one that was clicked underlined
$(this).addClass('currentlyActive');
});
});
</script>
而且,就是这样。我试图尽可能详细地解释每个步骤的作用。显然,您可以缩短类名并删除注释以使其更小更精简。
$("a").click(function() {
var $this = $(this);
$this.closest("div").find("a").removeClass("underlined");
$this.addClass("underlined");
});
然后,当然,您需要有一个名为“underlined”的类,它会在链接下划线。
这是一个更干净的版本:
<style type="text/css">
.underline { border-bottom:1px solid #000; }
</style>
<script type="text/javascript">
$(function() {
$('a').click(function() {
$('a').removeClass('underline');
$(this).addClass('underline');
});
});
</script>