2017-09-05 36 views
0

文件是这里使用的数组,并在其中传递了三个项目。在下一个button后,我只收到array的第一件物品。如何获得下一个项目onclick下一个button文件列表预览onclick

请找JS代码如下:

function plusSlides(n) { 

    var i; 
    var currentIndex= 0; 

    var files = ["","",""]; 
    if(currentIndex<files.length) 
{ 
    var omyFrame = document.getElementById("myFrame"); 
omyFrame.style.display="block"; 
omyFrame.src = files[currentIndex]; 
currentIndex++; 
    } 
n++; 
} 
+0

我认为你的代码片段没有提供足够的上下文。下一个按钮在哪里?请点击下一个按钮调用'plusSlides'? –

+0

将'if'改为'while'。另外,变量'i'和'n'是无用的 –

+0

将'if'改为'while'将在每次调用时设置iframe源三次,iframe将始终具有文件中最后一项的ssrc。 –

回答

0

你之所以只得到了数组的第一个项目每次都是因为你宣布currentIndexfilesplusSlides函数内。每次调用时,currentIndex都会重置为0

尝试把这些声明的plusSlides功能外:

var files = ['', '', '']; 
var currentIndex = 0; 

function plusSlides() { 
    ... 
} 
0

每次你打电话给你的功能,你重置你currentIndex变量,因为它是在你的函数的范围。你可以让你的currentIndex变量全局或保持当前索引的信息,你的函数:

function plusSlides(n) { 
 
    this.currentIndex = this.currentIndex || 0; 
 

 
    var files = ["", "", ""]; 
 
    if(this.currentIndex < files.length) 
 
    { 
 
     // Reset your iframe source here 
 
     this.currentIndex++; 
 
    } 
 
    console.log(this.currentIndex); 
 
}

0

值“n”要传递到功能未在函数内的任何地方使用。此外,变量i和currentIndex正在重置,所以在某种程度上这些变量在这里没有用处。您可以根据传递的参数更新currentIndex的值,然后相应地进行编码。 请尝试以下代码,

var currentIndex= 0; 
var files = ["","",""]; 

function plusSlides(n) { 
     if(n == 1) 
      currentIndex++; 
     else 
      currentIndex--; 
     currentIndex = (currentIndex <= -1)? 0 : currentIndex;   
     if(currentIndex<files.length) 
     { 
      var omyFrame = document.getElementById("myFrame"); 
      omyFrame.style.display="block"; 
      omyFrame.src = files[currentIndex]; 
     } 
    }