jQuery 替换类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12238884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:27:58  来源:igfitidea点击:

jQuery replace class

jquery

提问by MiFiHiBye

I have a large list of <li>'s that are given a width from a 'span3' class.

我有一个很大的<li>'s列表,它们的宽度来自 'span3' 类。

<ul class="thumbnails">
    <li class="span3">
        <div class="thumbnail"><img src="/images/logos-s/s-001.png" alt="" data-creator="swc"> <span>01</span></div>
    </li>
    repeat...40x
</ul>

I have buttons (button#grid-bigger&& button#grid-smaller) that allow the users to increase and decrease the size of the grid on click. Ideally, the user would be able to click three times, and each time it would change the <li>class from span3 to span4 then to span12.

我有按钮(button#grid-bigger&& button#grid-smaller),允许用户在点击时增加和减少网格的大小。理想情况下,用户可以单击 3 次,每次都会将<li>类从 span3更改为 span4,然后再更改为 span12。

Here's the JavaScript:

这是 JavaScript:

$('#grid-bigger').live('click', function (e) {
    $('#blob .thumbnails').find('li').each(function(i, ojb) {
        if ( $(this).hasClass('span2') ) {
            $(this).removeClass('span2').addClass('span3');
        }

        if ( $(this).hasClass('span3') ) {
            $(this).removeClass('span3').addClass('span4');
        }

        if ( $(this).hasClass('span4') ) {
            $(this).removeClass('span4').addClass('span12');
        }
    });
});

What happens is that instead of allowing separate clicks to the "make bigger" button, it'll only click once and execute two of the statements at the same time.

发生的情况是,它不允许单独单击“放大”按钮,而是只单击一次并同时执行两个语句。

Any suggestions?

有什么建议?

回答by Austin Greco

you just need to use else if, otherwise they will all execute in order:

您只需要使用else if,否则它们将按顺序执行:

if ( $(this).hasClass('span2') ) {
    $(this).removeClass('span2').addClass('span3');
} else if ( $(this).hasClass('span3') ) {
    $(this).removeClass('span3').addClass('span4');
} else if ( $(this).hasClass('span4') ) {
    $(this).removeClass('span4').addClass('span12');
}