Add class to element

2019-03-06 19:09发布

问题:

Like this, I have two tabs, so when i click on one it's active, logic. Now im trying to make difference between active and inactive tab, but not with .css property, but I wanna' add specific class to clicked tab, like this:

$(".tab1").addClass('active');

but, no good. Also have in mind that I'm using external css file.

<div id="menuitem" class="tab1"></div>
<div id="menuitem" class="tab2"></div>

.active {
    width: 170px;
    height: 70px;
    float: right;
    background-color: red;
}

#menuitem {
    width: 170px;
    height: 70px;
    float: right;
    background-color: white;
}

回答1:

First of all don't use same id on different elements, id's must be unique and try this:

jQuery:

$('.menuitem').click(function() {
    $('.menuitem').removeClass('active');
    //removes active class from all menu items

    $(this).addClass('active');
    //adds active class to clicked one
});

html:

<div id="tab1" class="menuitem"></div>
<div id="tab2" class="menuitem"></div>

css: you don't need to define same properties to active class, just define the difference:

.active { background-color: red; }

.menuitem {
  width: 170px;
  height: 70px;
  float: right;
  background-color: white;
}


回答2:

You can not have same id for two divs in HTML. Try changing your HTML like this.

<div id="menuitem1" class="menuitem tab1"></div>
<div id="menuitem2" class="menuitem tab2"></div>

.active {
background-color: red;
}

.menuitem {
width: 170px;
height: 70px;
float: right;
background-color: white;
}


回答3:

The other issue might be that you're running your jQuery function before the div element exists.

So either, move the code

$(".tab1").addClass('active');

below the div's you want to change, or wrap it in a document ready function.

$(document).ready(function(){
    $(".tab1").addClass('active');
});

which will wait till the dom has been created before running your code.



回答4:

First off, ids should always be unique.

The cause of your issue however, is css specificity. An id rule is more specific than a class one. Try this instead.

#menuitem.active {
width: 170px;
height: 70px;
float: right;
background-color: red;
}

#menuitem {
width: 170px;
height: 70px;
float: right;
background-color: white;
}

Keep in mind though that this will work to overcome the specificity issue. It does not address the fact that you need to get rid of your duplicated ids.

CSS Specificity



标签: jquery class add