Add and Remove class to click a dynamic Button

前端 未结 2 1998
太阳男子
太阳男子 2021-01-26 12:11

Trying to Add and Remove class to click dynamic Buttons, means this button get class dynamically like this:

2条回答
  •  無奈伤痛
    2021-01-26 12:53

    DEMO

    $('.label a').each(function () {
        var $this = $(this);
        $this.closest('li').addClass($this.text());
    });
    
    // Combine This
    $('button').each(function () {
        var liInd = 0;
        var cl = '';
        var txt = '';
        var clses = [];
        var ind = $('button').index($(this)) + 1;
        $('li').each(function () {
            if (clses.indexOf($(this).attr('class')) === -1) {
                clses.push($(this).attr('class'));
                liInd = liInd + 1;
            }
            if (ind === liInd) {
                cl = $(this).attr('class');
                txt = $(this).find('a').text();
                return false; //break
            }
        });
        $('button:nth-child(' + ind + ')').addClass(cl);
        $('button:nth-child(' + ind + ')').text(txt);
    });
    $(document).on('click', 'button',function(e){
        var textClass = $.grep(this.className.split(" "), function(v, i){
           return v.indexOf('text') === 0;
        }).join();
        console.log(textClass);
        $('li').removeClass('show').addClass('hide')
        $('li').each(function(){
        	if($(this).hasClass($.trim(textClass))){
            	$(this).removeClass('hide').addClass('show');
            } else {
                $(this).removeClass('show').addClass('hide');
            }
        })
    })
    .show{display:list-item;}
    .hide{display:none;}
    
    

提交回复
热议问题