[英]How to show only selected number of elements in array?
我開發了一個派對游戲只是為了娛樂,無法解決這個問題。 因此,首先我問用戶“您想看幾件衣服?”。 我將該數據設置為本地存儲,並在其他頁面上使用。 所以我的問題是:我只想顯示用戶選擇的數組中的元素個數(對不起我的英語不好,我真的很需要您的幫助)。 這是我的代碼:
index.html
<div class="container">
<div class="small-container">
<p id="text">How many clothes you want to choose ?</p>
<input type="number" placeholder="1 to 6" id="count" />
</div>
<button id="btn">Start</button>
</div>
script1.js
window.onload = function() {
var btn = document.getElementById("btn");
var count = document.getElementById("count");
btn.addEventListener("click", function() {
document.location.href = "random.html";
localStorage.setItem("count", count.value);
});
};
game.html
<div class="small-container">
<p id="text">Your random clothes: </p>
<img id="img" />
</div>
script2.js
var options = [
"T-Shirt",
"Singlet",
"Underwear",
"Socks",
"Shorts",
"Shoes"
];
var btn = document.getElementById("btn");
var text = document.getElementById("text");
var img = document.getElementById("img");
btn.addEventListener("click", function() {
var count = localStorage.getItem("count");
var randomChoice = options.splice(Math.floor(Math.random() * options.length), 1);
btn.innerHTML = "Shuffle";
text.innerHTML = randomChoice;
img.setAttribute("src", `img/${randomChoice}.png`);
if (randomChoice >= options.length) {
text.innerHTML = "End of game :)";
btn.innerHTML = "Start again";
img.removeAttribute("src");
btn.addEventListener("click", function() {
// document.location.href = "intro.html";
document.location.href = "random.html";
});
}
});
};
因此,每當用戶單擊按鈕時,衣服都在變化。 例如,如果用戶選擇4作為計數,我只想給他/她展示4件衣服,那么他們在每次點擊之前必須只能看到他們頁面上的一張圖像。
如果我正確理解了您的問題,那么您的問題是,一旦顯示了足夠的衣服,您就不知道如何停止游戲
這是一個解決方案
btn.addEventListener("click", function() {
var count = localStorage.getItem("count");
localStorage.setItem("count", count-1); //decreasing the value of count because one clothe is about to be shown on screen
if (count == 0) { //if count is at 0, that means game is over
text.innerHTML = "End of game :)";
btn.innerHTML = "Start again";
img.removeAttribute("src");
btn.addEventListener("click", function() {
// document.location.href = "intro.html";
document.location.href = "random.html";
});
}
else{ //we show a new cloth
var randomChoice = options.splice(Math.floor(Math.random() * options.length), 1);
btn.innerHTML = "Shuffle";
text.innerHTML = randomChoice;
img.setAttribute("src", `img/${randomChoice}.png`);
}
});
但是有了該代碼,仍然有可能多次拾取同一塊布。 為了避免這種情況,在將代碼保留為純JavaScript的同時,我想您可以使用“隱藏”輸入來存儲已顯示的衣服或其他localStorage變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.