簡體   English   中英

單擊按鈕后如何獲取數組的下一個項目?

[英]How can I get the next items of an array after clicking on a button?

我怎樣才能增加

var i = 0

每次我點擊

<div onClick="my()">

,所以只有數組的下一項被顯示並在最后一項之后重新啟動它?

<div onClick="my()" class="text"> 
                <p id="next-p"> Next</p> 
   

function my() {
var i = 0;
var names = [str1, str2, str3, str4, str5]; 
console.log(names[i]);
}

  1. i存儲在 function 的 scope 之外,因此每次調用 function 時都不會重新聲明為0
  2. 在 function 中增加i
  3. 您還會很快發現,只要i超過數組的長度,您就會想要重置它,因此向 function 添加一個條件來檢查它。

 var i = 0; var names = ['str1', 'str2', 'str3', 'str4', 'str5']; function my() { console.log(names[i++]); if (i === names.length) { i = 0; } }
 <div onClick="my()" class="text"> <p id="next-p"> Next</p> </div>

您必須從遞增它的 function 的 scope 外部設置要遞增的變量。

 let counter = 0; const names = ['John', 'Marie', 'James', 'Jim', 'Joe', 'Jack', 'Donald'] function increment() { counter++; // You should check whether the counter/index is out of bounds before accessing document.getElementById("counter").innerHTML = names[counter] || 'Out of bounds'; }
 <button onClick="increment()">Increment</button> <div id="counter">John</div>

使用您當前設置的代碼,每次調用 function 時, i變量都會重置為0 ,因此它將始終具有相同的值。

編輯:當心該解決方案越界:在進行任何數組訪問操作之前,您應該始終檢查計數器/索引的值以避免此類錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM