当值达到0时,立即更改按钮javascript

时间:2017-07-23 13:59:09

标签: javascript jquery

当我点击按钮时,用户HP下降到0,然后按钮发生变化。但更多的是,当userHealth达到零时,按钮没有改变。您必须再次单击按钮更改。怎么解决这个问题?

JS:

$(".attBtn").click(function() {

    var userId = 4;
    var attackdmg = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
    var userdmg = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
    var minimum = 0;    

    if(userHealth == 0){
        info.innerHTML = '<strong>'+user.textContent+'</strong> have been defeated.';
        attackBtn.css("backgroundColor", "blue");
        attackBtn.css("border", "none");
        innerAttBtn.innerHTML = "Get the reward <img src="+"/img/chest2.png"+"/> ";
        return false;           
    }else if(attackerHealth == 0){
        info.innerHTML = '<strong>You</strong> have been defeated.';
    }else if(attackerHealth == 0 && userHealth == 0){
        info.innerHTML = '<strong>DRAW FIGHT</strong>';
    }else{

    userHealth -= attackdmg;
    attackerHealth -= userdmg;

    document.getElementById('attackerBar').setAttribute("style","width:"+attackerHealth+"%");
    document.getElementById('userBar').setAttribute("style","width:"+userHealth+"%");

    $.ajax("/arena/fight-user/"+userId+"/attack/"+attackdmg+"/"+userdmg,
    {

    }); 

    if(userHealth < 0){userHealth = minimum;}
    if(attackerHealth < 0){attackerHealth = minimum;}

    userHp.innerHTML = '<strong>'+userHealth+'</strong>';
    attackerHp.innerHTML = '<strong>'+attackerHealth+'</strong>';

    info.innerHTML = '<strong>' +user.textContent+'</strong>' +' hit <strong>You</strong> with ' +userdmg+' dmg <br> ' + '<strong>You</strong> hit ' 
    +'<strong>'+user.textContent+'</strong>'+ ' with '+ attackdmg +' dmg';
}

});

1 个答案:

答案 0 :(得分:0)

存在逻辑缺陷。 原因是,为什么你必须再次点击,是因为你声明在HP 之前应该发生什么 HP实际上为零。

解决方案

把这个

userHealth -= attackdmg;
attackerHealth -= userdmg;
if(userHealth < 0){userHealth = minimum;}
if(attackerHealth < 0){attackerHealth = minimum;}

之前

if(userHealth == 0){
...