how to toggle attr() in jquery

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

    This answer is counting that the second parameter is useless when calling removeAttr! (as it was when this answer was posted) Do not use this otherwise!

    Can't beat RienNeVaPlus's clean answer, but it does the job as well, it's basically a more compressed way to do the ternary operation:

    $('.list-sort')[$('.list-sort').hasAttr('colspan') ? 
        'removeAttr' : 'attr']('colspan', 6);
    

    an extra variable can be used in these cases, when you need to use the reference more than once:

    var $listSort = $('.list-sort'); 
    $listSort[$listSort.hasAttr('colspan') ? 'removeAttr' : 'attr']('colspan', 6);
    

提交回复
热议问题