I ran into Don't load hidden images ... and wanted to run the function reveal
.
$(function () {
$("img").not(":visible").each(function () {
$(this).data("src", this.src);
this.src = "";
});
var reveal = function (selector) {
console.log("Viser billeder");
var img = $(selector);
img[0].src = img.data("src");
}
});
But how?
If I do this:
re开发者_运维技巧veal();
It returns this in the console:
reveal is not defined
How should I call this?
Define reveal in the global scope like this, it should work fine.
var reveal;
$(function () {
$("img").not(":visible").each(function () {
$(this).data("src", this.src);
this.src = "";
});
reveal = function (selector) {
console.log("Viser billeder");
var img = $(selector);
img[0].src = img.data("src");
}
});
reveal
will only be defined after:
var reveal = function (selector) {
console.log("Viser billeder");
var img = $(selector);
img[0].src = img.data("src");
}
And before the });
on the next line, since it is private to the anonymous function.
Edit
After looking at the code from your jsfiddle, you have another error. First of all the reason it's still not working is because after you took @ShankarSangoll's advice and added var reveal
in the outer scope, you kept the var
keyword in the inner scope as well so now you just have two variables named reveal
, the outer one is still undefined. If you remove var
from the inner one it will be defined.
However you have a $(function(){ ...});
inside a $(document).ready(function(){ ...};
which is redundant since you know the document is already ready inside your ready function. YOu can change your code to:
$(function() {
var reveal;
console.log("Billeder vises");
$("img").not(":visible").each(function() {
$(this).data("src", this.src);
this.src = "";
});
var reveal = function(selector) {
var img = $(selector);
img[0].src = img.data("src");
}
reveal();
});
Or remove the $(function(){ ...});
wrapper altogether since that delays your scripts. You'll also want to pass a selector to reveal()
, but I think you know that :)
You are accessing the variable outside of its scope. The var/function (reveal) is defined INSIDE of a parent function ( $(function(){... ), so it can only be used INSIDE of that parent function since it is LOCAL to it (just like any other local variable you define).
精彩评论