how to toggle attr() in jquery

前端 未结 10 2152
独厮守ぢ
独厮守ぢ 2021-01-30 15:50

I have a simple add attribute function:

$(\".list-toggle\").click(function() {
    $(\".list-sort\").attr(\'colspan\', 6);
});

My question is:

10条回答
  •  感动是毒
    2021-01-30 16:43

    This would be a good place to use a closure:

    (function() {
      var toggled = false;
      $(".list-toggle").click(function() {
        toggled = !toggled;
        $(".list-sort").attr("colspan", toggled ? 6 : null);
      });
    })();
    

    The toggled variable will only exist inside of the scope defined, and can be used to store the state of the toggle from one click event to the next.

提交回复
热议问题