【问题标题】:How do I replace special class with another in jquery?如何在 jquery 中用另一个类替换特殊类?
【发布时间】:2011-06-27 07:53:30
【问题描述】:

例如:

<li class="dataItem ready igto" status="ready">I will change status to waiting</li>

然后,我只想将ready class更改为waiting。正常的方法是删除 class ready 并添加新课程!

另一种情况是如何一次替换多类!?例如:

<!-- replace done wainting error to ready -->
<li class="dataItem done igto" status="ready">I will change status to ready</li>
<li class="dataItem waiting igto" status="ready">I will change status to ready</li>
<li class="dataItem error igto" status="ready">I will change status to ready</li>

到:

<li class="dataItem ready igto" status="ready">I will change status to waiting</li>

非常感谢!!

【问题讨论】:

    标签: jquery class replace


    【解决方案1】:

    最好的方法是照你说的做,删除类然后重新添加,因为 jQuery 中没有“切换”类。

    $('.dataItem').removeClass('ready').addClass('waiting');
    

    您可以通过将多个类传入.removeClass() 来替换多个类:

    $('.dataItem').removeClass('done waiting error').addClass('ready');
    

    【讨论】:

      【解决方案2】:

      您可以使用$.toggleClass() 来实现此目的。

      $("p").click(function(){
        // Replace 'done' with 'waiting' or 'waiting' with 'done'
        $(this).toggleClass("done waiting");   
      });
      

      示例:http://jsfiddle.net/wH9x3/

      【讨论】:

      • 不可靠,因为它每次都会切换,即使我们不想要它。
      • @sidney 重点是展示$.fn.toggleClass 的工作原理。由使用它的人有条件地包装它以仅在某些情况下执行。
      猜你喜欢
      • 1970-01-01
      • 2017-12-25
      • 2017-09-27
      • 1970-01-01
      • 2014-05-18
      • 2020-10-09
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      相关资源
      最近更新 更多