jQuery-根据条件删除类 [英] jquery - remove class based on condition

查看:61
本文介绍了jQuery-根据条件删除类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每1分钟轮询一次json响应,并根据该响应在页面上添加或删除覆盖.在大多数情况下,我的回答是肯定的,在这种情况下,我应该删除overlay类.在下面的代码中,else部分每次都在执行,而remove类和hide函数每次都在执行.有什么办法可以避免这种情况.jQuery中是否有任何方法可以检查是否添加了class.隐藏是否处于活动状态.或者任何人都可以通过设置和取消设置布尔变量来给出实现此目的的语法.

I am polling a json response for every 1 min and based on the response I am adding or removing overlay on my page. My response is most of the time positive , in this case , i should remove the overlay class. In the below code, else part is executing every time and remove class and hide functions are executed every time. Is there any way to avoid this . Is there any method in jquery to check whether class is added or not . Also hide is active or not. Or can anyone give syntax to achieve this by setting and unsetting a boolean variable.

(function poll() {
  setTimeout(function() {
    $.ajax({
      url: "path",
      type: "GET",
      success: function(data) {
        console.log("polling" + data);
        if (data.is_running === true) {
          $("#overlay").addClass('show');
          $("#alertDiv").show();
        } else {
          console.log("removing ....");
          $("#overlay").removeClass('show');
          $("#alertDiv").hide();

        }
      },
      dataType: "json",
      complete: poll,
      timeout: 200
    })
  }, 5000);
})();

推荐答案

您可以使用 toggle() toggleClass() >具有 Boolean 值的>,不需要 if ... else 语句,否则返回 false

You can use toggle() and toggleClass() with Boolean value no need of if...else statement otherwise returns false

$("#overlay").toggleClass('show',data.is_running);
$("#alertDiv").toggle(data.is_running);

要检查元素是否具有类,可以使用 hasClass() ,如果为匹配的元素分配了给定的类,则返回 true

And for checking that an element has a class or not you can use hasClass() which returns true if matched elements are assigned the given class

这篇关于jQuery-根据条件删除类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆