简体   繁体   English

在点击jquery上向元素添加特定的类

[英]adding specific class to element on click jquery

I'm having trouble with a simple nav bar that uses jQuery to add and remove a specific class when a certain page is active. 我在使用简单的导航栏时遇到麻烦,该导航栏在某些页面处于活动状态时使用jQuery添加和删除特定的类。 I want a class to append to my aLink class depending on which ID is click. 我希望根据单击的ID将一个类追加到我的aLink类中。 If I click on #aboutLink I want .linkActive to be added, but if I click on #sasLink I want .link2Active to be added. 如果单击#aboutLink .linkActive添加.linkActive ,但是如果单击#sasLink .link2Active添加.link2Active The tutorials I've looked at all have a single class being added, but since both my classes are different I need a specific one to be added depending on which ID is click. 我看过的所有教程都添加了一个类,但是由于我的两个类都不相同,因此我需要根据单击的ID添加一个特定的类。

HTML: HTML:

<div id="mainNav">
    <ul id="nav">
        <a id="mainLogo" href="/"><li></li></a>
        <a id="aboutLink" class="aLink" href="/"><li></li></a>
        <a id="sasLink" class="aLink" href="/savings-and-support"><li></li></a>
        <a id="external" href="/"><li></li></a>
    </ul>
</div><!--/#mainNav-->

I know my jQuery doesn't make sense, but it's all I could come up with. 我知道我的jQuery没有意义,但这就是我能想到的全部。 Logically I get it, but I'm lost on the syntax. 从逻辑上讲我明白了,但是我对语法一无所知。

jQuery: jQuery的:

$(function () {
    $(".aLink").click(function () {
        if ($(this) == $("#aboutLink")
            $(this).addClass('activeLink');
         else $(this).addClass('active2Link');
         });
     });

Thanks for any input or direction. 感谢您的任何输入或指示。

var idToClass = {
    'aboutLink' : 'linkActive',
    'sasLink' : 'link2Active'
}

$('#nav a').click(function(){
    e.preventDefault();
    $(this).addClass(idToClass[this.id]);
});

JS Fiddle demo . JS小提琴演示

You could, instead, use toggleClass() to allow for those classes to be removed by a second click: 您可以改为使用toggleClass()允许通过再次单击删除这些类:

var idToClass = {
    'aboutLink' : 'linkActive',
    'sasLink' : 'link2Active'
}

$('#nav a').click(function(e){
    e.preventDefault();
    $(this).toggleClass(idToClass[this.id]);
});

JS Fiddle demo . JS小提琴演示

Edited in response to question, from the OP, in comments, below: 根据OP的问题进行编辑 ,评论如下:

How would I remove the class so that both links don't appear to be active at the same time? 我将如何删除该类,以使两个链接不会同时处于活动状态?

There's a few ways, but because you're adding different class-names to denote the 'active' state, they're a little inefficient. 有几种方法,但是由于要添加不同的类名来表示“活动”状态,因此它们效率低下。 The first approach is to use a brute-force method, effectively looking for all a elements that have a class attribute and setting that attribute to the empty string, and then adding the linkActive / link2Active class-name to the clicked-on a element: 第一种方法是使用蛮力方法,有效地查找所有具有class属性a元素并将该属性设置为空字符串, 然后linkActive / link2Active类名添加到所单击a元素上:

$('#nav a').click(function(e){
    e.preventDefault();
    var self = $(this);
    self.closest('ul').find('a[class]').attr('class', '');
    self.toggleClass(idToClass[this.id]);
});

JS Fiddle demo . JS小提琴演示

The alternative is to remove the specific classes from the elements who have their id listed in the idToClass object. 另一种方法是从idToClass对象中列出其id的元素中删除特定的类。 This is, however, somewhat expensive in that it needs to iterate over the object, retrieving the id , finding the element with that id and then removing a class -name: 但是,这有点昂贵,因为它需要遍历对象,检索id ,找到具有id的元素 然后删除class -name:

$('#nav a').click(function(e){
    e.preventDefault();
    for (var id in idToClass) {
        if (idToClass.hasOwnProperty(id)){
            $('#' + id).removeClass(idToClass[id]);
        }
    }
    $(this).addClass(idToClass[this.id]);
});

JS Fiddle demo . JS小提琴演示

If, of course, you use a common class-name then it all becomes much easier: 当然,如果您使用通用的类名,那么一切将变得容易得多:

$('#nav a').click(function (e) {
    e.preventDefault();
    var self = $(this);
    self.closest('ul')
        .find('.commonActiveClassName')
        .removeClass('commonActiveClassName');
    self.addClass('commonActiveClassName');
});

JS Fiddle demo . JS小提琴演示

References: 参考文献:

Since you already have ID tags to easily reference... I think you want something more like this? 既然您已经具有ID标记以方便参考...我想您想要更多类似的东西吗?

$(function () {
    $("#aboutLink").click(function () {
            $(this).addClass('activeLink');
    });
    $("#sasLink").click(function () {
            $(this).addClass('active2Link');
    });
});

Try using this instead: 尝试使用此代替:

$(function () {
    $(".aLink").click(function () {
        var currentId = this.id;
        if ( currentId == "aboutLink"){
            $(this).addClass('activeLink');
         else if( currentId == "sasLink") {
             $(this).addClass('active2Link');
         }
     });
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM