减去硬币价值

时间:2015-07-22 09:42:04

标签: javascript jquery

我想减去我的价值并保存。
所以例如

500个硬币。我创建了按钮“购买”。我的物品需要花费80个硬币而且我需要(500 - 80),价值会保存。

<p id = "coins"> 500 </p>       
<script>
   var coins = 500;
   document.getElementById("coins").innerHTML= (500 - 80);
   document.getElementById('button').onclick = function() {
     if (coins>80) {
        alert("You successfully bought this item!");
     }
     if (coins<80) {
        alert("You do not have much money");
     }
   }
</script>

并且无论用什么语言都无关紧要。即使如此,也可以寻求帮助:)

2 个答案:

答案 0 :(得分:0)

使用jquery

    <p id="coins">500</p>
    <input type="button" id="button" value="Buy" />
   -- Jquery
    $('#button').click(function () {
        var coins = $('#coins').text();
        var rem_coins = coins - 80;
        if (rem_coins > 80) {
            alert("You successfully bought this item!");
            $('#coins').text(rem_coins);
        }
        else if(rem_coins < 80)
        {
            alert("You do not have much money");
        }    
    });

演示Jsfiddle

答案 1 :(得分:0)

  

当我按下按钮时,我想从p(在我的情况下是500)中读取硬币值,然后减去500 - 80并显示警告。< / p>

&#13;
&#13;
var coins = parseInt(document.getElementById("coins").innerHTML, 10);

document.getElementById('button').onclick = function() {
    
    if ( coins < 80 )   {
        alert("You do not have much money");
        return;   
    }
    alert("You successfully bought this item!");
    coins -= 80; // equal to coins = coins - 80;
    document.getElementById("coins").innerHTML = coins;   
}
&#13;
<p id="coins">500</p>

<button id="button">Click Me</button>
&#13;
&#13;
&#13;