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/