开发者

How to make a load response have several conditions in it?

I have a function

function preloadImage() {
varLink=".... link to my picture..."
$("#picture").attr("src", varLink).one("load", function() {
 // This is called after the image is loaded
 }}

Now I call this function many times in my jquery script. But I need it to call different functions after the image is loaded. Is there any more elegant way to do that instead of sending parametrs to function like:

function preloadImage(action)

and making several if then statements after the function is executed to replace the: // This is called after the image is loaded in my code?

So I basically need to do several things after image is loaded (callback) so I ha开发者_开发技巧ve to call this function with several different parameters or is there any other way?

Thank you

Jerry


You could pass the function itself in, for example:

function preloadImage(callback) {
  varLink=".... link to my picture..."
  $("#picture").one("load", callback).attr("src", varLink);
}

Then you can call it passing the function, for example

function doSomething() {
  alert("I'm loaded!, my src is: " + this.src);
}
preloadImage(doSomething);

You may want to pass the image link as well, I'm unclear from your example, but it seems likely you would want to, here's an example of that, with an anonymous function:

//define it
function preloadImage(imageUrl, callback) {
  $("#picture").one("load", callback).attr("src", imageUrl);
}

//example call
preloadImage('myImage.jpg', function () { 
  alert("I'm loaded!, my src is: " + this.src);
});

One last thing to keep in mind, you should bind the load event handler before setting the src, to make sure it fires in all cases (from cache for example), just like I have above.


Edit, adding version for comments:

function preloadImage(callback) {
  varLink=".... link to my picture..."
  $("#picture").one("load", function() {
    callback.apply(this, arguments);
    $('#ajax-loader').hide();
  }).attr("src", varLink);
}

There's an alternative as well, keep it simple and bind the "every time" function separately, like this:

//this handler happens on all future loads
$("#picture").load(function() { $('#ajax-loader').hide(); });

//this handler runs just once for this load
function preloadImage(callback) {
  varLink=".... link to my picture..."
  $("#picture").one("load", callback).attr("src", varLink);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜