我如何点击一个链接,该链接保持一个类,直到我点击另一个?

时间:2011-01-24 08:59:53

标签: jquery hyperlink

嗨我想知道如何点击一个保持课程的链接,直到我点击另一个,它将从中删除该课程,而我刚刚点击的课程将返回该课程?

//animation for secondary content pics
$('#small li').hover(function () {
    $(this).addClass('small_list_hover');
}, function () {
    $(this).removeClass('small_list_hover');
});

$("h4").append('<em> Image 1</em>').show();

$("#small a").click(function () {
    var largePath = $(this).attr("href");
    var largeAlt = $(this).attr("title");
    $('li').removeClass('small_li_hover');
    $('this').addClass('small_li_hover');
    $('#largeImg').hide().fadeIn(1000).attr({
        src: largePath,
        alt: largeAlt
    });
    $("h4 em").html(" " + largeAlt + " ");
    return false;
});

3 个答案:

答案 0 :(得分:4)

你可以这样做:

$(document).ready(function() {
   $("a").click(function() {
      $("a").removeClass("active");
      $(this).addClass("active");
   });
});

答案 1 :(得分:1)

试试这个......

 $("a").click(function(){
   $("a.active").removeClass("active");
   $(this).addClass("active");
});

DEMO

根据问题它应该像是 $("#small a").click(function () {
var largePath = $(this).attr("href");
var largeAlt = $(this).attr("title");
$('li').removeClass('small_li_hover');
$(this).parents('li').addClass('small_li_hover');
$('#largeImg').hide().fadeIn(1000).attr({
src: largePath,
alt: largeAlt
});
$("h4 em").html(" " + largeAlt + " ");
return false;
});

答案 2 :(得分:0)

$("#small a").click(function () {
    var largePath = $(this).attr("href");
    var largeAlt = $(this).attr("title");



    //$('li').removeClass('small_li_hover'); 
    // $('this').addClass('small_li_hover'); // your problem is here....
    $(this).closest('li').addClass('small_li_hover')
           .siblings().removeClass('small_li_hover');


    $('#largeImg').hide().fadeIn(1000).attr({
        src: largePath,
        alt: largeAlt
    });
    $("h4 em").html(" " + largeAlt + " ");
    return false;
});

  

嗨Reigel,我试过了,但它没有   工作。当我将链接悬停在它上面时   class自行删除!

嗯,我并不感到惊讶。那么,我们这样做怎么样,

改变,

$(this).closest('li').addClass('small_li_hover')
       .siblings().removeClass('small_li_hover');

之类的,

$(this).closest('li').addClass('small_li_active')
       .siblings().removeClass('small_li_active');

然后在你的CSS上,如果你有类似的东西,

.small_li_hover {
   color: red;
}

将其更改为

.small_li_active,
.small_li_hover {
   color: red;
}

simple demo