[英]JavaScript Alert won't trigger
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 blocks
。
尝试这个-
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>
尽管已经接受了答案,但是尝试找到解决方案还是很有趣的,所以我只是重新创建了整个过程,对其进行了简化,创建了用于反馈的功能(摆脱了alert
),并添加了“ Kill Me”按钮。 :)
这是我想出的(感谢@vikrant singh的“代码段”标记):
healthval = $("#health").val(); function feedback(healthval) { if (healthval >= 1) { $('#msg').text("It's already full!"); } else if (healthval === 0) { $('#msg').text("Your critter has died! Oh no!"); } else { $('#msg').text("You give your critter some food!"); } } $(document).ready(function () { $('.heal').click(function () { healthval = $("#health").val(); $("#health").val(healthval + 0.1); console.log(healthval); feedback(healthval); }); $('.kill').click(function () { healthval = $("#health").val(); $("#health").val(healthval - 0.1); console.log(healthval); feedback(healthval); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.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> <button type="button" class="kill">Kill Me</button> <div id="msg"></div>
这是小提琴链接,因此您可以根据自己的喜好对其进行编辑: http : //jsfiddle.net/uruws5ov/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.