JavaScript警报赢得';t触发器
JSJavaScript警报赢得';t触发器,javascript,Javascript,JS var health = document.getElementById("health") $(document).ready(function(){ $('.heal').click(function(){ var healthval = +document.getElementById('health').getAttribute('value') console.log(health
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>
治癒我
在我正在进行的一个小项目中,我正在使用上面的“健康栏”代码。 我对它很满意,因为它的健康状况应该是上升/下降的。唯一的问题是,出于某种原因,
警报(“它已经满了!”)代码>和警报(“你的小动物死了!哦,不!”)代码>部分没有在应该发生的时候发生……但是警报(“你给你的小动物一些食物!”)代码>每次都会触发
我做错了什么?组合语句if(healthval==1)
&if(healthval>1)
在检查同一变量的条件时,最好使用if-else-block
而不是只使用if-blocks
试试这个-
var health=document.getElementById(“health”)
$(文档).ready(函数(){
$('.heal')。单击(函数(){
var healthval=document.getElementById('health').getAttribute('value')*1;
如果(healthval>=1){
警报(“已经满了!”);
}else if(healthval==0){
警惕(“你的小动物死了!哦,不!”);
}否则{
document.getElementById('health').setAttribute('value',healthval+0.1);
console.log(healthval)
警惕(“你给你的小动物一些食物!”);
}
});
});代码>
治愈我
虽然答案已经被接受,但我在尝试找到解决方案时还是很开心,所以我只是重新创建了整个过程,简化了它,创建了一个反馈函数(去掉了警报
),并添加了一个“杀死我”按钮。:)
以下是我的想法(感谢@vikrant singh提供的“代码片段”标记):
healthval=$(“#health”).val();
函数反馈(healthval){
如果(healthval>=1){
$('#msg').text(“已经满了!”);
}else if(healthval==0){
$(“#msg”).text(“你的小动物死了!哦,不!”);
}否则{
$('msg').text(“你给你的小动物一些食物!”);
}
}
$(文档).ready(函数(){
$('.heal')。单击(函数(){
healthval=$(“#health”).val();
$(#health”).val(healthval+0.1);
console.log(healthval);
反馈(healthval);
});
$('.kill')。单击(函数(){
healthval=$(“#health”).val();
$(#health”).val(healthval-0.1);
console.log(healthval);
反馈(healthval);
});
});代码>
治癒我
杀了我
因为它总是会在其他部分结束!你看过你的控制台了吗healthval
实际上永远不会变成1或0…我一直在写这个项目,不知道如何在上面查看控制台。我该如何修改它以使healthval发生变化?由于您没有动态值,请同意@DhavalMarthakThank!工作得很漂亮,又好又紧凑。呵呵,很高兴你喜欢它;)