这是我的代码:
$(window).load(function() {
var theImage = $('ul li img');
var theWidth = theImage.width();
//wrap into mother div
$('ul').wrap('<div class="gallery-slide" />');
//assign height width and overflow hidden to gallery-slide
$('.gallery-slide').css({
width: function() {
return theWidth;
},
height: function() {
return theImage.height();
},
position: 'relative',
overflow: 'hidden'
});
//get total of image sizes and set as width for ul
var totalWidth = theImage.length * theWidth;
$('ul').css({
width: function() {
return totalWidth;
}
});
});
$('ul li img').each(function(intIndex) {
$(this).nextAll('a').bind("click", function() {
if ($(this).is(".next")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex + 1) * theWidth)
}, 1000);
} else if ($(this).is(".previous")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex - 1) * theWidth)
}, 1000);
} else if ($(this).is(".startover")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (0)
}, 1000);
}
}); //close .bind()
}); //close .each()
上面是我的代码,它抛出错误theWidth
is not Defined。
最佳答案
JavaScript has
function-level
scope(beforeECMAScript 6
), if a variable declared inside some block of code enclosed bycurly braces
is only visible within that block of code, and that variable is not visible outside of that particular block of code.
theWidth
是在 $(window).load
的范围内定义的,而 undefined
超出了 的范围。加载
处理程序。
将所有代码包装在 load
处理程序中。
$(window).load(function() {
var theImage = $('ul li img');
var theWidth = theImage.width();
//wrap into mother div
$('ul').wrap('<div class="gallery-slide" />');
//assign height width and overflow hidden to gallery-slide
$('.gallery-slide').css({
width: function() {
return theWidth;
},
height: function() {
return theImage.height();
},
position: 'relative',
overflow: 'hidden'
});
//get total of image sizes and set as width for ul
var totalWidth = theImage.length * theWidth;
$('ul').css({
width: function() {
return totalWidth;
}
});
$('ul li img').each(function(intIndex) {
$(this).nextAll('a').bind("click", function() {
if ($(this).is(".next")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex + 1) * theWidth)
}, 1000);
} else if ($(this).is(".previous")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (-(intIndex - 1) * theWidth)
}, 1000);
} else if ($(this).is(".startover")) {
$(this).parent('li').parent('ul').animate({
"margin-left": (0)
}, 1000);
}
});
});
});
关于javascript - 当我编写脚本时,它显示 ReferenceError : theWidth is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36905388/