我有两种语言的JSON,这是 Shuffle 开始。我想让它重新开始,如果索引的JSON是按下按钮等于最大索引。但是我被困在这里,因为我对JavaScript并不熟悉。请帮助使它,以便单击WINE按钮返回到shuffled JSON的开头。
// Detect language into variable and log it
var userLang = navigator.language || navigator.userLanguage;
console.log("The browser language is: " + userLang);
var alcoscroll = {
"wine": [{
"en": "Wine Drink 1",
"es": "Vino 1",
}, {
"en": "Drink 2",
"es": "Vino 2",
}, {
"en": "Drink 3",
"es": "Vino 3",
}, {
"en": "Drink 4",
"es": "Vino",
}]
};
alcoscroll.wine.sort(function (alcoscroll) {return Math.random() - 0.5;}); // Sort alcoscroll
console.log(alcoscroll);
var index = 0; // Starting index of JSON object
var maxx = alcoscroll.wine.length-1; // Max ID number (JSON index number)
var item = alcoscroll.wine[index]; // Current index sniffer
var next = document.getElementById('refbtn'); // Button to move to next one
displayItem(item);
next.addEventListener('click', function() {
displayItem(alcoscroll.wine[++index]);
});
console.log("MAXIndex is: " + maxx)
function displayItem(item) {
// Catch item number into function ERROR HERE
intitem = alcoscroll.wine[index];
console.log("INT item is: " + intitem);
// English or Spanish radical choice
if (userLang === "en-US") {
title.innerText = item.en;
} else {
title.innerText = item.es;
}
console.log("Index is: " + index)
if (intitem == maxx) { // If it's the last index of JSON object ERROR HERE
console.log("LAST")
next.addEventListener('click', function() {
intitem = 0; // Current index sniffer ERROR HERE
});
} else
{console.log("NOT last")}
}
<div class="container">
<div>
<div id="title"></div>
</div>
<button id="refbtn">WINE</button>
</div>
1条答案
按热度按时间nwo49xxi1#
问题就出在这段代码中:
当您应该比较
index
和maxx
时,您正在比较intitem
和maxx
。此外,您不需要添加另一个事件侦听器,只需重置index
值即可。将其更改为:以下是更新后的代码片段: