开发者

jquery: remove previous class by clicking

I've a very simple question but can't figure it out by myself. i've the following problem.

i've several list items like below.

<li></li>
            <li>
                <img src="images/persoon1.jpg" alt="persoon1">
                <div id="infoPersoon">
                    <h3>Jaap-Jan van der Gouw</h3>
                    <ul id="contactInfo">
                        <li class="label">T</li>
                        <li>070 31 31 066</li>
                        <li class="label">F</li>
                        <li>070 31 31 066</li>
                        <li class="label">M</li>
                        <li>070 31 31 066</li>
                    </ul>
                    <ul id="contactOpties">
                        <li class="email"><a href="#" class="active">Email</a></li>
                        <li class="publicaties"><a href="#">Publicaties</a></li>
                        <li class="vcard"><a href="#">Vcard</a></li>
                        <li class="meerinfo"><a开发者_如何学运维 href="#">Meer info</a></li>
                    </ul>
                </div>
            </li>
            <li></li>

the problem is that i want to add a class by the current list i clicked on, and when i clicked to the next list item, the previous class "active" must be remove.

how can i solve that problem.


The most common approach is to remove the active class from any tag that has it like:

$(".active").removeClass("active");

To put it all together would be:

$("li").click(function() {
    $(".active").removeClass("active");
    $(this).addClass("active");
});


You can add a click handler like this:

$("#contactOpties li a").click(function() {
  $(this).addClass('active')
         .parent().siblings().children().removeClass('active');
});

You can give it a try here. This adds the class only on click, but you could also toggle the .active class off if you clicked, do to that use .toggleClass() instead of .addClass().


Or just so you have options, you could have the click handler on the <li> or use .delegate() (useful for lots of elements, or dynamically changing ones), like this:

$("#contactOpties").delegate("li", "click", function() {
  $(this).children('a').addClass('active').end()
         .siblings().children().removeClass('active');
});

You can give that a try here.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜