.onblur函数作为variable.value返回

.onblur function return as a variable.value?

本文关键字:value 返回 variable 函数 onblur      更新时间:2023-09-26

http://jsfiddle.net/beY6d/

我想制作一个简单的HTML+JS页面,基本上给用户4个文本字段来写一些产品的名称,并在第5个文本字段中显示剩余信用。

<input type="text" value="0" class="product" id="shirtItems"/><br>
<input type="text" value="0" class="product" id="pantsItems"/><br>
<input type="text" value="0" class="product" id="hatItems"/><br>
<input type="text" value="0" class="product" id="accesoryItems"/><br>
<input type="text" value="100" id="credit" disabled/>

var shirt= document.getElementById("shirtItems");
var pants= document.getElementById("pantsItems");
var hat= document.getElementById("hatItems");
var accesory= document.getElementById("accesoryItems");
var remainingDosh = document.getElementById("credit");
remainingDosh.value = 100;

必须有一个.onblur(或.onfocus)事件,才能使"信用"字段显示100减去其他项目的总和。

此外,商品的价格必须根据商品的颜色/类型而变化。类似于:

shirt.onblur = function(){
    if (shirt.value == "Blue") {remainingDosh.value = remainingDosh-25}
    if (shirt.value == "Red") {remainingDosh.value = remainingDosh-20;}
};

如果执行typeof remainingDosh.value,您将看到它记录string。这意味着,如果你不想冒NaN出现在页面上的风险,你必须将字符串转换为数字。

parseInt()这样转换:

var remainingDosh.value = parseInt(remainingDosh,10)-25;

第二个参数10是基数,在这种情况下是十进制的(尽管我认为如果省略,它默认为十进制)。

正如所指出的,有问题的是,你试图对元素remainingDosh进行数学运算,而不是使用它的value

哦,还有protip:您可以使用this.value,而不是shirt.value,因为事件来自上述元素。

进行减法运算时,使用的是remainingDosh而不是remainingDosh.value