开发者

How do I add and remove classes with jQuery?

I have ul list with a link in each li. My question is: how do I remove the class 'selected' from one a (anchor) and apply it to the one I hover over?

<ul>
    <li><a href="" class="selected">Link 1</a></li>
    <li><a href="">Link 2</a></li>
    <li><a href="">Link 3</a></li>
    <li><a hr开发者_如何学Goef="">Link 4</a></li>
    <li><a href="">Link 5</a></li>
</ul>


checkout the jquery api: http://api.jquery.com/

jQuery.addClass jQuery.removeClass

$("li").hover(
  function () {
    $(this).addClass('selected');
  }, 
  function () {
    $(this).removeClass('selected');
  }
);


Try this:

$("ul li a").hover(function(e){
    $("ul li a").removeClass("selected");    
    $(this).addClass("selected");
    e.preventDefault();
});

You remove it from all the a tags on hover then add it to the one that the mouse is on.


you need to write a selector to find the right node and then use the method addClass and removeClass

in this case

$(".selected").removeClass("selected").addClass("unselected");

note how i chained the two together..


$('li').mouseover(function(){
     $(this).addClass('selected');
    console.log("adding class");
}
).mouseout(function(){
    $(this).removeClass('selected');
    console.log("removing class");
});

Working sample: http://jsfiddle.net/MdNXZ/


With the following HTML:

<ul>
    <li><a href="">Link 1</a></li>
    <li><a href="">Link 2</a></li>
    <li><a href="">Link 3</a></li>
    <li><a href="">Link 4</a></li>
    <li><a href="">Link 5</a></li>
</ul>

The JQuery script line for what you ask would be:

$('li').hover( $(this).children('a').toggleClass('selected') );

That's it. A one liner.

Docs for the functions:

http://api.jquery.com/hover/

http://api.jquery.com/toggleClass/

http://api.jquery.com/children/


0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜