gpt4 book ai didi

函数的 Javascript JQuery 最佳实践

转载 作者:行者123 更新时间:2023-11-30 18:38:47 26 4
gpt4 key购买 nike

我正在尝试 github,我想我会在那里放一个小的测试项目。因为它是公开的,所以我通过 JSHint 运行我,但我得到一个我无法摆脱的错误:

Line 21 preloadImages();

'preloadImages' is not defined.

这是代码:

$(function() {

var allImagesLoaded = false, imagesLength = 0, counter = 0, imageArray = [], loadedImages = [], loadedImagesCounter = 0;

/*--------------------------------
Add your images to the array
and your good to go
--------------------------------*/
imageArray = ["img/1.jpg", "img/2.jpg", "img/3.jpg", "img/4.jpg"];
imagesLength = imageArray.length;

if(imagesLength === 0) {
$('#container').html('<p><strong>You need to put some images in your array</strong></p>');
}
else {

preloadImages();
}

function preloadImages() {
var tempImage = $("<img />").attr("src", imageArray[loadedImagesCounter]);

tempImage.load(function(){

loadedImages.push(this);
loadedImagesCounter++;
if(loadedImagesCounter == imagesLength) {
imageArray = loadedImages;
initEverything();
}
else {
if(!allImagesLoaded)
{
preloadImages();
}
}
});
}

function initEverything() {


allImagesLoaded = true;
$('#preloadingImages').hide();

// Deactivate the context menu that appears on right click
$(document).bind("contextmenu", function(e) {
return false;
});

var theSource = $(imageArray[0]).attr('src');

var theImage = $('<img />');
$(theImage)
.attr('src', theSource)
.attr('width', imageArray[0].width)
.attr('height', imageArray[0].height)
.attr('alt', 'demobild 1')
.attr('id', 'pageImage');

$('#container').append(theImage)

$("#pageImage").mousedown(function(e) {
if (allImagesLoaded) {
switch (e.which) {
case 1:
stepForward();
break;
case 2:
// center button on the mouse
break;
case 3:
stepBackward();
break;
default:
// Nada
}
}
});
$(document).keydown(function(e) {
e.preventDefault();
if (allImagesLoaded) {
switch (e.keyCode) {
case 37: // Left
stepBackward();
break;
case 38: // Up
stepBackward();
break;
case 39: // Right
stepForward();
break;
case 40: // Down
stepForward();
break;
default:
// Nada
}
}
});

}

function stepForward() {

if (counter === imagesLength-1) {
counter = 0;
} else {
counter++;
}
$("#pageImage").attr("src", $(loadedImages[counter]).attr('src'));
$("#pageImage").attr("alt", "demobild " + counter);
}

function stepBackward() {

if (counter === 0) {
counter = imagesLength-1;
} else {
counter--;
}
var sourcePath = $(imageArray[counter]).attr('src');
$("#pageImage").attr("src", sourcePath);
$("#pageImage").attr("alt", "demobild " + counter);
}

});

放置函数的最佳实践在哪里?在顶部?

这是我的项目 https://github.com/Benjaminsson/Image-expo

最佳答案

JavaScript 将函数声明提升到作用域的开头。因此,该函数在整个范围内(传递给 $() 的函数)都可用,无论它在哪里定义。 JSLint 可能无法正确检测到这一点,并认为该函数在您调用它时处于未定义状态。

关于函数的 Javascript JQuery 最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7470306/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com