jQuery fade + replace issue
I am brand new to javasript and jQuery, and I'm trying to make a simple script to fade out an image and replace it with a random one.
The following works when the next image to be faded is not referred to as "curImg". I thought maybe my nextImg function was failing to produce, but it appears to be preparing an 开发者_开发知识库accurate image location string (why I have the alert function).
Anywhere you see my error(s), I'd appreciate any help! thanks so much, and sorry for the novice level code XD.
$.fn.preload = function() {
this.each(function(){
$('<img/>')[0].src = this;
});
}
function nextImg() {
var curImg = "images/";
var randomNumber=Math.floor(Math.random()*11)
curImg += randomNumber;
curImg += ".jpg";
alert(curImg);
$([curImg]).preload();
}
nextImg();
$("document").ready( function() {
$("#umom1").animate({
opacity: 0
}, 1900,function() {
$("#umom1").attr("src", curImg);
$("#umom1").animate({
opacity: 1
}, 1900);
});
});
You have a variable scope issue, curImg
is not defined in global scope, it's defined in local function scope, so you can't access it from anywhere other than the function itself.
Because you used the var
keyword within the nextImg()
function, the variable's lifetime is restricted to that function only.
I suggest returning the curImg
variable from nextImg()
, like so:
function nextImg() {
var curImg = "images/";
var randomNumber = Math.floor(Math.random()*11);
curImg += randomNumber;
curImg += ".jpg";
alert(curImg);
$([curImg]).preload();
return curImg;
}
Your ready
function should then look like this:
$(document).ready(function() {
var img = nextImg();
$("#umom1").fadeOut(1900, function() {
$("#umom1").attr("src", img);
$("#umom1").fadeIn(1900);
});
});
精彩评论