开发者

jQuery addClass() not working given an ID

I have the following jQuery code:

$.ajax({
  type: "POST",
  url: "/search",
  data: $("form").serialize(),
  success: function(data) {
    $("#tab").addClass("loading"); // THIS LINE DOESN'T WORK
    // . . . LOAD SEARCH RE开发者_JAVA技巧SULTS HERE (USUALLY TAKES SEVERAL SECONDS) . . .
    $("#tab").removeClass("loading");
  }
});

And I have the following CSS:

.loading {
  background: transparent url(../resources/images/loading.gif) no-repeat right center;
  text-indent: -1000px;
}

And I have the following relevant HTML:

<div id="tab">
  <table id="searchResultsGrid"></table>
</div>

I can't get the line $("#tab").addClass("loading") to work. Watching in FireBug, the class .loading is never added to the #tab object. What am I doing incorrectly?

Thanks!


Try this instead. What's probably happening is that it's adding and removing the loading class quickly enough that it steps on itself

// add the class before the ajax call
$("#tab").addClass("loading");

$.ajax({
  type: "POST",
  url: "/search",
  data: $("form").serialize(),
  success: function(data) {
    // . . . LOAD SEARCH RESULTS HERE . . .
  }
  complete: function(data) {
    // remove the class on complete, not success, in case of an error
    $("#tab").removeClass("loading");
  }
});


Without seeing the HTML, it's hard to say, but one thing that stands out is that you're adding the class once the ajax call returns with a success. Try changing to this:

$("#tab").addClass("loading");

$.ajax({
  type: "POST",
  url: "/search",
  data: $("form").serialize(),
  success: function(data) {
    // . . . LOAD SEARCH RESULTS HERE . . .
    $("#tab").removeClass("loading");
  }
});


You should set the class prior to the ajax call and then remove it in the success function. What you are doing is setting it and then removing it in the same code execution. The class will not visually update until the code completes execution, at which point you have already removed the class.


first you addClass loading ,then you removeClass loading ,that's why you didn't see it working , you should add loading class before the ajax call, when the call returns success, you can removeClass

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜