JavaScript 警报不会触发

标签 javascript

JS

    var health = document.getElementById("health")

    $(document).ready(function(){ 
        $('.heal').click(function(){
                var healthval = +document.getElementById('health').getAttribute('value')
                console.log(healthval)
                if (healthval === 1) {
                    alert("It's already full!");
                } else {
                    document.getElementById('health').setAttribute('value', healthval + 0.1);
                    alert("You give your critter some food!");
                }      
                if (healthval > 1) {
                    healthval = 1;
                }
                if (healthval === 0) {
                    alert("Your critter has died! Oh no!");
                }
            });
    });


HTML

<meter low=".5" optimum=".8" high=".7" id="health" value="0.1"></meter>
<button type="button" class="heal">Heal Me</button>


我在我正在进行的一个小项目中将上面的代码用于“健康栏”。 我对它很满意,因为它的健康状况确实像预期的那样上升/下降。唯一的问题是,出于某种原因,alert("It's already full!");alert("Your critter has died! Oh no!"); 部分是在它们应该发生的时候发生......但是 alert("You give your critter some food!"); 每次都会触发。

我做错了什么?

最佳答案

合并语句 if (healthval === 1)if (healthval > 1) 并且更好地使用 if else block 而不是仅当您检查同一变量的条件时,if block

试试这个-

var health = document.getElementById("health")

$(document).ready(function () {
    $('.heal').click(function () {
        var healthval = document.getElementById('health').getAttribute('value') * 1;
        if (healthval >= 1) {
            alert("It's already full!");
        } else if (healthval === 0) {
            alert("Your critter has died! Oh no!");
        } else {            
            document.getElementById('health').setAttribute('value', healthval + 0.1);
            console.log(healthval)
            alert("You give your critter some food!");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<meter low=".5" optimum=".8" high=".7" id="health" value="0.1"></meter>
<button type="button" class="heal">Heal Me</button>

关于JavaScript 警报不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25926713/

相关文章:

javascript - jQuery 从输入字符串中添加/删除文本

javascript - 有没有更有效的方法来打开字符串数组的每个元素?

javascript - 如何在javascript中设置图像的自动宽度

javascript - 选择 2 : Creating tags with ajax

javascript - 遍历我的sql结果并循环显示

javascript - React 组件中的 render() 函数的作用是什么?

javascript - JS全局变量保持不变

javascript - 我不明白 JavaScript 中的递归

JavaScript游戏——无法跨越的物体

javascript - 使用 <p> 标签包装 JQuery 函数结果