當前,當單擊兩個按鈕之一時,陣列中的所有值都會立即顯示。我的目標是默認顯示第一個值,并使用下一個/上一個顯示下一個/上一個陣列條目。
我怎樣才能簡單地意識到這一點?
var array = ["text1", "text2", "text3"];
function next(){
//Next text in Array
document.getElementById('text').innerHTML = array.join('<br />');
}
function prev(){
//Previous text in Array
document.getElementById('text').innerHTML = array.join('<br />');
}
<div id="siggen">
<div style="background-color: orange; height: 150px; width: 300px" id="content">
<p id="text"></p>
</div>
<button id="btnPrev" onclick="prev()">Previous</button>
<button id="btnNext" onclick="next()">Next</button>
</div>
uj5u.com熱心網友回復:
像這樣的東西?
var array = ["text1", "text2", "text3"];
let currentIndex = 0;
let currentId = array[0];
log(currentId);
function next(){
move();
}
function previous(){
move(false);
}
function move(advance = true){
currentIndex = (currentIndex (advance ? 1 : -1) array.length) % array.length;
currentId = array[currentIndex];
log(currentId);
}
function log(currentId){
document.getElementById('text').innerHTML = currentId;
}
<p id="text"></p>
<button onclick="next();">Next</button>
<button onclick="previous();">Previous</button>
另外,我從這個問題中得到了代碼,我只更改了代碼以使其在標簽p上顯示文本
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/478724.html
標籤:javascript html
