使用jQuery编辑HTML ID值

时间:2014-09-17 00:04:27

标签: jquery

我试图制造一个小小动物&#39;一个项目的游戏。 我最近发现了<meter>的美丽,并决定将其用于我的健康状况&#39;和幸福&#39;杆

HTML

<meter low=".5" optimum=".8" high=".7" id="health" value="0.1"></meter>
<button type="button" id="feedme">Feed Me</button>

JS

var health = document.getElementById("health")
$(document).ready(function(){
    $('#feedme').click(function(){
        if (health === 1) {
            confirm("I'm already full!");
        } else {
            document.getElementById('health').setAttribute('value', + 0.5);
            confirm("Ewww, I really hate brussel sprouts");
        }      
        if (health > 1) {
            health = 1;
        }
    });
});

以上代码改变了健康状况&#39; ID为0.5而不是添加0.5。我相信这是因为我使用.setAttribute()而不是别的。

我尝试了几种不同的方式,包括health.value = food;(增加食物而不是食物)和其他更长的解决方案,由于声誉不足,我无法在此处链接< / p>

那么,我可以使用哪些代替.setAttribute()修改而不是设置呢?

JSfiddle

1 个答案:

答案 0 :(得分:1)

好的,这使得它至少可以按米计算(除了在IE上)。你游戏的UX肯定是由你定义的。%)P。

unary plus operatorhttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Unary_plus_(.2B)

var health = document.getElementById("health")
$(document).ready(function(){
    $('#feedme').click(function(){
        var val = + document.getElementById('health').getAttribute('value') //unary + to Integer

        if (val > 1) {
            val = 1;
        }

        if (val === 1) {
            confirm("I'm already full!");
        } else {
            document.getElementById('health').setAttribute('value', val + 0.5);
            confirm("Ewww, I really hate brussel sprouts");
        }      

    });
});

JSFIDDLE