我正在用JavaScript进行图像幻灯片演示,为了更好地理解代码,我将function slideshow(n)
的参数更改为function slideshow(slideIndex)
,但是注意到它没有用,请您帮我弄清楚这两者之间有什么区别函数的参数,为什么函数slideshow(slideIndex)
中的第二个参数不起作用?
var slideIndex = 1;
slideshow(slideIndex);
function nextPrev(n){
slideshow(slideIndex += n);
}
function slideshow(slideIndex){
// why "function slideshow(slideIndex)" stops executing after some
// slides, however function slideshow(n) works properly here?
var x = document.getElementsByClassName("slide");
var dot = document.getElementsByClassName("dot");
if(slideIndex > x.length) slideIndex = 1;
if(slideIndex < 1) slideIndex = x.length;
for(var i=0; i < dot.length; i++){
dot[i].className = dot[i].className.replace(" active", "");
}
for(var i = 0 ; i < x.length; i++){
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
dot[slideIndex-1].className += " active";
}
最佳答案
参数变量始终是局部变量。因此,当您使用slideIndex
作为参数变量时,它会以相同的名称遮盖全局变量。
结果,当您这样做时:
if(slideIndex > x.length) slideIndex = 1;
if(slideIndex < 1) slideIndex = x.length;
它只会影响局部变量,而不会影响全局变量,因此当函数返回时,这些更改不会持久。
如果函数要更新全局变量,则实际上没有充分的理由将其作为索引。
function nextPrev(n) {
slideIndex += n;
slideshow();
}
function slideshow() {
var x = document.getElementsByClassName("slide");
var dot = document.getElementsByClassName("dot");
if (slideIndex > x.length) {
slideIndex = 1;
} else if (slideIndex < 1) {
slideIndex = x.length;
}
for (var i = 0; i < dot.length; i++) {
dot[i].className = dot[i].className.replace(" active", "");
}
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex - 1].style.display = "block";
dot[slideIndex - 1].className += " active";
}
或者,您可以将根据数组限制检查
slideIndex
的代码放在调用方中,并使slideshow()
仅仅显示幻灯片而无需更新slideIndex
。function nextPrev(n) {
var slideCount = document.getElementsByClassName("slide").length;
slideIndex += n;
if (slideIndex > slideCount) {
slideIndex = 1;
} else if (slideIndex < 1) {
slideIndex = slideCount;
}
slideshow(slideIndex);
}
function slideshow(slideIndex) {
var x = document.getElementsByClassName("slide");
var dot = document.getElementsByClassName("dot");
for (var i = 0; i < dot.length; i++) {
dot[i].className = dot[i].className.replace(" active", "");
}
for (var i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex - 1].style.display = "block";
dot[slideIndex - 1].className += " active";
}
另外,使用
1
作为数组索引时,不要减去slideIndex
,而应将其值设置为0
到length-1
而不是1
到length
。在处理数组索引时习惯于从0
开始计数。关于javascript - 替换函数中的参数不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52428551/