gpt4 book ai didi

javascript - 如何仅显示数组中选定数量的元素?

转载 作者:行者123 更新时间:2023-12-02 23:12:23 24 4
gpt4 key购买 nike

我开发了一个聚会游戏只是为了好玩,并不能解决这个问题。所以,首先我问用户“你想看多少件衣服?”。我将该数据设置到本地存储,并在其他页面上使用。所以我的问题是:我只想显示用户在数组中选择的元素数量(我很抱歉我的英语不好,我真的需要你的帮助)。这是我的代码:

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>

脚本1.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);
});
};

游戏.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`);
}
});

但是使用该代码仍然有可能多次选择同一 block 布料。为了避免这种情况,在将代码保持在纯 JavaScript 中的同时,我想您可以使用“隐藏”输入来存储已显示的衣服或其他 localStorage 变量。

关于javascript - 如何仅显示数组中选定数量的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57290776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com