最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery remove class from many, add class to one - Stack Overflow

programmeradmin0浏览0评论

A mon operation I find myself doing is the following:

<ul>
    <li>One</li>
    <li class="current">Two</li>
    <li>Three</li>
</ul>

var $allLi = $('li');

$allLi.click(function(){
    $allLi.removeClass('current');
    $(this).addClass('current');
});

Is there a way to condense this, somehow by bining $allLi and $(this) and using toggleClass?

Thanks!

A mon operation I find myself doing is the following:

<ul>
    <li>One</li>
    <li class="current">Two</li>
    <li>Three</li>
</ul>

var $allLi = $('li');

$allLi.click(function(){
    $allLi.removeClass('current');
    $(this).addClass('current');
});

Is there a way to condense this, somehow by bining $allLi and $(this) and using toggleClass?

Thanks!

Share Improve this question asked Apr 27, 2012 at 18:59 HandiworkNYC.HandiworkNYC. 11.1k25 gold badges95 silver badges156 bronze badges 1
  • 1 What you are doing is about as efficient as it can be using jQuery methods. – Kevin B Commented Apr 27, 2012 at 19:07
Add a ment  | 

2 Answers 2

Reset to default 5

Jonathan's solution should work just fine but I would like to propose a different solution.

Rather than unsetting all the elements and then selecting the current one, why not just keep track of the current element and only perform the operation on that?

<ul>
    <li>One</li>
    <li class="current">Two</li>
    <li>Three</li>
</ul>

<script type="text/javascript">
    (function () {
        var current = $("li.current");
        $("li").click(function () {
            current.removeClass("current");
            current = $(this);
            current.addClass("current");
        });
    }());
</script>

It's "longer" but also more efficient.

My solution aims to have all state in JavaScript rather than partly in the DOM. toggleClass circumvents this principle. It's not so much a matter of "hey looks this a really long and super plex way of doing something simple", there's an idea behind it. If your application state gets more plex than just one selected element you'll run into issues if you try and stuff that state into the DOM. The DOM is just a 'view', keep your state in the 'model' (the JS code).

I believe you could add it, and remove it from the siblings:

$("li").on("click", function(){
  $(this)
    .addClass("current")
    .siblings()
      .removeClass("current");
});

Demo: http://jsbin./owivih/edit#javascript,html,live

发布评论

评论列表(0)

  1. 暂无评论