开发者

How can I replace image inside a TD with loading image during Ajax call

开发者 https://www.devze.com 2023-01-26 19:05 出处:网络
I have an HTML table. In each cell there is an image followed by some text. Something like this: <td>

I have an HTML table. In each cell there is an image followed by some text. Something like this:

<td>
  <img src='image.gif'>This is a test
</td>

I have to run a jQuery Ajax call and during this call I want to change the image to a loading image that I have (loading.gif) and then return it to the regular image (image.gif in this case) after the Ajax 开发者_如何学JAVAis complete.

What is the correct jQuery syntax to change the image to the loading image and back again?


I believe your question is regarding how to change an image before an AJAX Request and then change it back when the AJAX request is finished.

Well below is a sample...and here is some reference to the jQuery ajax() method. Note: the ajax() method contains options to declare success, error and complete function that can be executed when the AJAX call is successful, errors out, or is completed (ie after either success or error).

<td>
  <img id="loadingImg" src='image.gif'>This is a test
</td>

$("#loadingImg").attr("src", "loading.gif");
$.ajax({ //other options here
  complete: function () {
  $("#loadingImg").attr("src", "image.gif");  // change image back when ajax request is complete
} });


To change the image is relatively easy:

$('img[src="image.gif"]').attr('src','path/to/new/image.png');

The selector could be improved if your image had an id ($('#imageIDname'), which would apply only to that one image element) or class ($('.imageClassName') though that would apply to all images of that class-name). I don't know if you want to apply this to all images in all tds or just to one particular img element.

Coupling that to your ajax call is a little trickier, since I have no idea what your ajax call looks like.

Also, and this might be just my obsessiveness, your element should look like:

<img src='image.gif' />This is a test

Note the trailing / in the img tag.

0

精彩评论

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