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); }
$('#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/
这应该有所帮助
$("a").on("click", function(e){ e.preventDefault(); $(this).addClass("active"); $(this).siblings().removeClass("active"); });