jQuery:如果单击它,则将链接添加到链接

我在链接上调用jquery函数onclick。 例如:

Content 1 Content 2 Content 3 

如您所见,第一个链接默认为“活动”类。 我想从第一个链接中删除该类并添加到单击的链接。 为此,我试图在Animate2id函数中添加以下行:

 $('.active').removeClass('active'); $(this).addClass('active'); 

它只是从链接中删除了类。 但是这并没有将类添加到任何链接中。 我该如何解决这个问题?

编辑:这里是完整的jQuery函数:

 function Animate2id(id){ var animSpeed=2000; var $container=$("#container"); if(ease){ var easeType=ease; } else { var easeType="easeOutQuart"; } $container.stop().animate({"left": -($(id).position().left)}, animSpeed, easeType); } 

如果在具有id的父元素中包含标记,则可以执行以下操作:

 $('#parent_element_of_links a').click(function(e) { e.preventDefault(); $('#parent_element_of_links a').removeClass('active'); $(this).addClass('active'); }); 

工作示例: http : //jsfiddle.net/fDZ97/

您也可以将上面的代码放在您Animate2id()函数中:

 function Animate2id(id, ease) { var animSpeed = 2000; var $container = $("#container"); if (ease) { var easeType = ease; } else { var easeType = "easeOutQuart"; } $container.stop().animate({ "left": -($(id).position().left) }, animSpeed, easeType); // remove "active" class from all links, add it to this one $('#parent_element_of_links a').removeClass('active'); $(this).addClass('active'); }​ 

更新

this关键字无效,因为它指的是窗口而不是链接。 所以我在函数中添加了一个额外的参数,它现在运行得很好,只需记住在onclick中添加this (在定义ease变量之前):

 function Animate2id(id, t, ease) { var animSpeed = 2000; var $container = $("#container"); if (ease) { var easeType = ease; } else { var easeType = "easeOutQuart"; } $container.stop().animate({ "left": $(id).position().left }, animSpeed, easeType); // remove "active" class from all links, add it to this one $('#links a').removeClass('active'); $(t).addClass('active'); }​ 

工作jsFiddle示例: http : //jsfiddle.net/Uqqmy/

更好的方法是从锚标记中删除函数调用,而是创建一个jQuery事件处理程序。

我在jsfiddle中有一个例子:

http://jsfiddle.net/3AKU3/

这应该有所帮助

 $("a").on("click", function(e){ e.preventDefault(); $(this).addClass("active"); $(this).siblings().removeClass("active"); }); 

好的,谢谢你粘贴代码,试试这个:

首先将一组锚标记包装在div中,这样您就可以将它们从页面上的其他锚点中分离出来,然后将它们分组:

所以:

  

然后尝试这个JQuery代码:

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