how do I remove a class if an element has a class that I'm looking for using jQuery?
<a href='1.html' onclick='return false' class='selected'>video 1</a>
<a href='2.html' onclick='return false' class=''>video 2</a>
<a href=开发者_StackOverflow'3.html' onclick='return false' class=''>video 3</a>
<a href='4.html' onclick='return false' class=''>video 4</a>
In the above code, I have 4 possible menus that appear depending on which link tag I click. Whenever I click on a link that is not selected and doesn't have the 'selected' class, I want to remove the 'selected' class from the previously selected video link tag, and add that class to the link that is being clicked on.
I have no problem adding the class to the link that is being clicked on, but how do I remove the class 'selected' from the currently selected link tag when I click on a different link?
I tried the following and it did not work
$('a').hasClass('selected').removeClass('selected');
but apparently it is not a proper function and gives me an error message in the error log in firefox.
.hasClass()
returns a boolean. Just use the selector API appropriately:
$('a.selected').removeClass('selected');
That said, this is logically equivalent:
$('a').removeClass('selected');
$("a.selected").removeClass("selected");
$('a').click(function(e){
// current link
var $link = $(this);
// find all siblings (fellow links) and remove selected class
$link.siblings('a.selected').removeClass('selected');
// make sure this class has the elected class
$link.addClass('selected');
});
精彩评论