开发者

adding a class on click of Anchor tag

Lets say I have the following HTML...

<a class="act开发者_如何学Goive" href="#section1">Link 1</a>  
<a href="#section2">Link 2</a>  

When a link 2 is clicked I would like it to receive the active class and remove the class from link 1 itself so it would effectively become:

<a href="#section1">Link 1</a>  
<a class="active" href="#section2">Link 2</a>

This should work both ways. Ie. whatever link is clicked gets the class and removes it from the other.

How can this be done with jQuery? Thanks in advance!


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

Edit: added jsfiddle

http://jsfiddle.net/LJ6L5/


Just use: addClass and removeClass

But first limit your activable links with second class ('activable') to not affect other links on page:

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

With HTML:

<a class="activable active" href="#section1">Link 1</a>  
<a class="activable" href="#section2">Link 2</a>  


HTML:

<a class="myrefclass" href="#section1">Link 1</a>  
<a class="myrefclass active" href="#section2">Link 2</a>

JS:

var ref = $("a.myrefclass");
$(ref).bind('click', function() {

   if (!$(this).hasClass("active")) {

      $(ref).removeClass("active");
      $(this).addClass("active);
   }

});

JS II (for comment):

var ref = $("a.myrefclass");
$(ref).bind('click', function(ev) {

   if (!$(this).hasClass("active")) {
      ev.stopPropagation();
      return false;
   }

   $(ref).removeClass("active");
   $(this).addClass("active);

});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜