gpt4 book ai didi

javascript - 我希望不显示0,在FULL之前保持显示0

转载 作者:行者123 更新时间:2023-12-02 18:16:56 25 4
gpt4 key购买 nike

我有一个带有 javascript 和 localStorage 的简单程序。有一个等于 10 的变量槽。当我单击“扣除”时,它会递减。但问题是它在 document.getElementById('slot').innerText = "FULL"; 之前显示 0(零)。会触发。我不知道为什么。我想要的是当插槽达到 0 时,它不会显示零,而是显示 FULL。

Javascript:

    window.onload = function(){
slot = localStorage.getItem("slot");

if (slot == null) {
slot = 10;
}

document.getElementById("slot").innerText = slot;
document.getElementById("button1").addEventListener('click', function(e){
e.preventDefault();
reduceSlot();
})
}

function reduceSlot() {
if (slot >= 1) {
slot--;
document.getElementById("slot").innerText = slot;
localStorage.setItem("slot", slot);
}
else {
document.getElementById('slot').innerText = "FULL";
document.getElementById("button1").style.display = "none";
}
}

HTML:

<p id="slot">10</p>
<a href="javascript:reduceSlot(1)" id="button1">Deduct</a>
<button onclick="window.localStorage.clear();">Clear All</button>

这是链接: http://jsfiddle.net/K8stQ/

最佳答案

目前还不太清楚你想要什么,但如果你希望 last 元素为 1,那么这就是解决方案:

而不是

if (slot >= 1) {

使用

if (slot > 1) { //simply "greater", instead of "greater or equal"

为什么需要这个?让我们清理这个 block :

if (slot >= 1) { //checks if slot is greater than, or equal to 1. 
slot--; // **in this case**, equivalent to slot = slot-1;
document.getElementById("slot").innerText = slot; //set the value of slot to element
localStorage.setItem("slot", slot);
}
else {
document.getElementById('slot').innerText = "FULL";
document.getElementById("button1").style.display = "none";
}

现在让我们看看出了什么问题。

  • 调用的方法
  • 插槽为2

    • 如果条件计算结果为true,则执行该分支
    • 槽已减少,槽现在为1
    • 槽(1)的值设置为元素
    • 方法结束
  • 再次调用方法

  • 插槽为1

    • 如果条件计算结果为true,则执行该分支
    • 槽位减少,槽位现在为0 -- 哎呀,这是我们不想要的
    • 槽(0)的值设置为元素
    • 方法结束
  • 再次调用方法

  • 插槽为0
    • 如果条件计算结果为,则执行 else 分支
    • FULL设置为元素
    • 方法结束

那么要做什么:提前停止 1 步:不允许槽达到 1...

关于javascript - 我希望不显示0,在FULL之前保持显示0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19198021/

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