jQuery - Add active class and remove active from other element on click

前端 未结 6 2221
独厮守ぢ
独厮守ぢ 2020-12-14 09:24

I\'m new to jQuery, so I\'m sorry if this is a silly question. But I\'ve been looking through Stack Overflow and I can find things that half work, I just can\'t get it to f

6条回答
  •  别那么骄傲
    2020-12-14 10:15

    Use jquery cookie https://github.com/carhartl/jquery-cookie and then you can be sure the class will stay on page refresh.

    Stores the id of the clicked element in the cookie and then uses that to add the class on refresh.

            //Get cookie value and set active
            var tab = $.cookie('active');
            $('#' + tab).addClass('active');
    
            //Set cookie active tab value on click
            //Done this way to preserve after page refresh
            $('.topTab').click(function (event) {
                var clickedTab = event.target.id;
                $.removeCookie('active', { path: '/' });
                $( '.active' ).removeClass( 'active' );
                $.cookie('active', clickedTab, { path: '/' });
            });
    

提交回复
热议问题