$(document).ready(function() {
function loadSlide(url, zIndex, initLeft){
slide = $("<img />").attr("src", url).on("load", function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
console.log("broken image!");
} else {
$("#my_slider").append(slide);
slide.css({
"z-index": zIndex,
"left": initLeft
});
}
});
}
loadSlide("img/man_slide1.png", 100, "0vw");
loadSlide("img/man_slide2.png", 99, "0vw");
});
我无法解决这个问题。如您所见,我希望多次调用相同的函数来加载多个图像。但只有最后一个在我的浏览器中加载(并在Inspector中检查)。
我做错了什么?
答案 0 :(得分:2)
我明白了:
slide = $("<img />").attr("src", url).on("load", function() {
需要不是全局变量,而是函数范围的本地变量,如下所示:
var slide = $("<img />").attr("src", url).on("load", function() {
编辑,为清楚起见,我也将函数放入变量中:
$( document ).ready(function() {
$.loadImage = function loadSlide(url, zIndex, initLeft, className){
var slide = $("<img />").attr("src", url)
.on("load", function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
console.log("broken image!");
} else {
$("#my_slider").append(slide);
slide.css({"z-index": zIndex, "left": initLeft}).addClass(className);
}
});
}
$.loadImage("img/man_slide1.png", 100, "-100vw", "slide1_1");
$.loadImage("img/man_slide2.png", 99, "-100vw", "slide2_1");
$.loadImage("img/man_slide3.png", 98, "-100vw", "slide3_1");
$.loadImage("img/man_slide4.png", 97, "100vw", "slide4_1");
});