2017-09-05 40 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]; 
     } 
    }