使用jquery更改类onClick [英] Change class onClick using jquery

查看:71
本文介绍了使用jquery更改类onClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用class =active显示活动状态的导航。点击链接后,我需要将活动类添加到点击的链接,然后从所有其他链接中删除活动类。

I have a navigation that shows an active state using class="active". When a link is clicked, I need to add the "active" class to to the clicked link, and remove the "active" class from all other links.

这是我的代码:

<div id="referNav">
<div id="referLink1"><a href="javascript:;" onClick="changeClass();" class="active"></a></div>
<div id="referLink2"><a href="javascript:;" onClick="changeClass();" class=""></a></div>
<div id="referLink3"><a href="javascript:;" onClick="changeClass();" class=""></a></div>
</div>

任何帮助都将不胜感激!

Any help would be greatly appreciated!

推荐答案

试试这个:

function changeClass() {
    $('#referNav a').removeClass('active');
    $(this).addClass('active');
}

你还应该在javacript中绑定函数,如下所示:

And you should also bind the function in javacript like so:

$('#referNav a').on('click', changeClass);

这样,正如Travis J在评论中指出的那样, $(这个)将引用正确的对象。

That way, as Travis J points out in the comments, $(this) will reference the correct object.

jsFiddle

这篇关于使用jquery更改类onClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆