I'm setting two local variables inside of a jQuery .load(function(){...})
handler, but I can't find a way to access those variables outside of the handler. I tried removing the var
declaration, but that didn't work. Now I'm trying to use return
, but I can't get it to work either. Instead of alerting a numerical value, Firefox is alerting "[object HTMLImageElement]" when I run the code.
*I can verify that al开发者_运维问答ert(x)
works when placed inside the handler/function.
The code below is a modification of Xavi's solution to reading the actual dimensions of an image.
var imagepopXY = $("<img/>").attr('src', imagepopSrc).load( function() {
var x = this.width;
var y = this.height;
return [x,y]
});
alert (imagepopXY[0]);
imagepopXY contains the image and not the function !
So you can't call it like this.
If you want to define global variables, define them before the function :
var x; var y;
var imagepopXY = $("<img/>").attr('src', imagepopSrc).load( function() {
x = this.width;
y = this.height;
});
but this is not a very good code !
imagepopXY will contain the image, as Jerome already pointed out. The bigger problem is that even in Mrchief's solution the alert won't show you those values. Why? Because the load event fires when the image is actually loaded and in most cases that will likely be after the alert triggers (since you're assigning those values in an event, the rest of the code keeps chugging along without any regard for it).
If your application needs the x and y values before it can continue then it would be best to just put a function call inside the load event. Like this:
$("<img/>").attr('src', imagepopSrc).load(function() {
keepWorkingWithTheImage(this.width, this.height);
});
var keepWorkingWithTheImage = function(x, y) {
// your code is here
alert(x);
alert(y);
};
Try it like this:
var imagepopXY = {};
$("<img/>").attr('src', imagepopSrc).load( function() {
imagepopXY.x = this.width;
imagepopXY.y = this.height;
});
alert ('X: ' + imagepopXY.x + ' Y: ' + imagepopXY.y);
精彩评论