Ok, I know there is something simple going on here that I'm missing, all I'm trying to开发者_高级运维 do is store an object returned from a jQuery query like
var obj = $("#objectID");
as a global vand then reference it from within a function.
The example below serves a picture of a dog but then uses jQuery to swap the src attribute of the image to show a cat. What am I missing?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<!-- jquery -->
<script src="jquery-1.6.1.min.js" type="text/javascript" language="javascript"></script>
<!-- image swap -->
<script type="text/javascript" language="javascript">
// a global jQuery object
var globalMainImage = $("#mainImage");
// a global integer
var globalInteger = 420;
$(document).ready(function() {
/* this works
$("#mainImage").hide();
$("#mainImage").attr("src", "http://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Youngkitten.JPG/800px-Youngkitten.JPG");
$("#mainImage").fadeIn(1500);
*/
/* and this works
var localMainImage = $("#mainImage");
localMainImage.hide();
localMainImage.attr("src", "http://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Youngkitten.JPG/800px-Youngkitten.JPG");
localMainImage.fadeIn(1500);
*/
/* and this works
alert(globalInteger);
*/
/* but this doesn't */
globalMainImage.hide();
globalMainImage.attr("src", "http://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Youngkitten.JPG/800px-Youngkitten.JPG");
globalMainImage.fadeIn(1500);
});
</script>
</head>
<body>
<img id="mainImage" src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/250px-YellowLabradorLooking_new.jpg" />
</body>
</html>
var globalMainImage = $("#mainImage");
is outside of document.ready, the element doesnt' exist at the time this code is executed.
Do this:
var globalMainImage
$(document).ready(function() {
globalMainImage = $("#mainImage");
}
That's because it calculates that before the document is ready. It needs to go inside the document.ready().
精彩评论