单击链接时的JavaScript添加类 [英] JavaScript Add Class When Link is Clicked

查看:53
本文介绍了单击链接时的JavaScript添加类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些链接:

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

单击链接2时,我希望它接收活动的类并从链接1本身中删除该类,这样它就可以有效地变为:

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>

这应该同时起作用.IE.单击任何链接都将获取该类,并将其从另一个类中删除.

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

如何使用JavaScript/Prototype做到这一点?

How can this be done with JavaScript/Prototype?

推荐答案

您可以使用 prototype 支持从所有 active 元素中删除该类,并将其添加到被单击的元素中:

You could write a little helper function with prototype support that removes the class from all active elements and adds it to the one that was clicked on:

function active(e) {
    $$('.active').each(function(i) {
        i.removeClassName('active');
    });
    e.addClassName('active');
};

您可以从您的 onclick 事件中调用此函数:

You can than call this function from your onclick events:

<a href="#sectiona" onclick="active(this)">a</a>
<a href="#sectionb" onclick="active(this)">b</a>
<a href="#sectionc" onclick="active(this)">c</a>

这篇关于单击链接时的JavaScript添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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