how to toggle attr() in jquery

前端 未结 10 1928
独厮守ぢ
独厮守ぢ 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:35

    For what it's worth.

    $('.js-toggle-edit').on('click', function (e) {
        var bool = $('.js-editable').prop('readonly');
        $('.js-editable').prop('readonly', ! bool);
    })
    

    Keep in mind you can pass a closure to .prop(), and do a per element check. But in this case it doesn't matter, it's just a mass toggle.

    0 讨论(0)
  • 2021-01-30 16:37
    $("form > .form-group > i").click(function(){
        $('#icon').toggleClass('fa-eye fa-eye-slash');
    
        if($('#icon').hasClass('fa-eye')){
            $('#Password1').attr('type','text');
        } else {
            $('#Password1').attr('type','password');
        }
    });
    
    0 讨论(0)
  • 2021-01-30 16:43

    If you're feeling fancy:

    $('.list-sort').attr('colspan', function(index, attr){
        return attr == 6 ? null : 6;
    });
    

    Working Fiddle

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题