Add and Remove class to click a dynamic Button

前端 未结 2 1972
太阳男子
太阳男子 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 13:09

    Here is an alternative solution

    $('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
            }
        });
    
        if (txt != '') {
            $('button:nth-child(' + ind + ')').addClass(cl);
            $('button:nth-child(' + ind + ')').text(txt);
        }
    });
    
    $('button').click(function () {
        if ($(this).attr('class')[0] == 'all') {
            showAll();
            return false; // end this function
        }
    
        var allCls = $(this).attr('class').split(' ');
    
    
    
        $('li').each(function () {
    
            if (allCls.indexOf($(this).find('a').text()) > -1) {
                $(this).closest('li').removeClass('show').addClass('hide');
            } else {
                $(this).closest('li').removeClass('hide').addClass('show');
            }
        });
    });
    
    function showAll() {
        $('li').removeClass('hide').addClass('show');
    }
    

    Fiddle: https://jsfiddle.net/taleebanwar/yaLm4euk/13/

提交回复
热议问题