我想创建一个简单的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/>
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
必须有.onblur(或.onfocus)事件使" 信用 "字段显示100减去每个其他项目的总和.
此外,商品的价格必须根据商品的颜色/类型而改变.就像是:
shirt.onblur = function(){
if (shirt.value == "Blue") {remainingDosh.value = remainingDosh-25}
if (shirt.value == "Red") {remainingDosh.value = remainingDosh-20;}
};
Run Code Online (Sandbox Code Playgroud)
如果你这样做typeof remainingDosh.value,你会看到它记录string.这意味着如果您不想冒险NaN在页面上显示,则必须将字符串转换为数字.
转换它parseInt()是这样的:
var remainingDosh.value = parseInt(remainingDosh,10)-25;
Run Code Online (Sandbox Code Playgroud)
第二个参数10是基数,在这种情况下是十进制(虽然如果省略,它默认为十进制)我相信.
正如所指出的那样,问题在于你是在尝试对元素进行数学运算remainingDosh而不是使用它value.
哦,和protip:shirt.value你可以使用,this.value因为事件来自所述元素.
| 归档时间: |
|
| 查看次数: |
658 次 |
| 最近记录: |