jQuery:如果点击则添加类来链接 [英] jQuery: adding class to link if its clicked
问题描述
我在链接上调用jquery函数onclick。例如:
I call jquery function onclick at links. For example:
<a class="active" href="#" onClick="Animate2id('#box1');" >Content 1</a>
<a href="#" onClick="Animate2id('#box2');" >Content 2</a>
<a href="#" onClick="Animate2id('#box3');" >Content 3</a>
正如你可以看到的,第一个链接默认为active。我想从第一个链接中删除类,并添加到被点击的链接。
为此,我试图在Animate2id函数内添加以下行:
As you can see, first link has by default class 'active'. I want to remove the class from first link and add to the link which is clicked. For that purpose, I'm trying to add following line inside the Animate2id function:
$('.active').removeClass('active');
$(this).addClass('active');
它只是从链接中删除类。
但是这不会将类添加到任何链接。
It just removes the class from the link. But this does not add the class to any of the link. How I can fix that?
编辑:
这里是完整的jQuery函数:
Here is complete jQuery function:
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);
}
推荐答案
c $ c>< a> 标签,您可以这样做:
If you have the <a>
tags in a parent element with an id, you can do this:
$('#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 ()
函数:
You could also just put the code above in your Animate2id()
function that you have:
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');
}
h2>
此
关键字无效,因为它指的是窗口而不是链接。所以我在函数中添加了一个额外的参数,它现在工作得很好,只需记住在onclick中添加 this
(在定义 ease
variable):
Update
The this
keyword wasn't working because it was referring to the window rather than the link. So I added an extra parameter in the function and it works perfectly now, just remember to add this
in the onclick (right before you define the ease
variable):
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/
Working jsFiddle Example: http://jsfiddle.net/Uqqmy/
这篇关于jQuery:如果点击则添加类来链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!