我的商品“item1成本为1美元”,“item2成本为2美元”
如果客户购买超过 50件(总商品= item1 + item2),我会用一个简单的形式计算两者的总价格我会给他50%的折扣,这意味着只有当总数超过“50”时,最终价格才会除以2但是。
即使总数仅为10,我得到的价格除以2!
这是jsfiddle: http://jsfiddle.net/2yTLp/225/
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
var total = x.value + y.value;
if( total >= 50 ){
d.innerHTML = ((x.value * 1.00) + (y.value * 2.00)) / 2;
}
else{
d.innerHTML = (x.value * 1.00) + (y.value * 2.00);
}
}
x.onblur = calculate;
calculate();
#d{
text-indent:20px;
}
<h3>Calculate</h3>
item1 <input id="x" data-in="" type="number" /><br>
<br>
item2 <input id="y" data-in="" type="number" /><br>
<br>
Please Pay and amount of <span id="d"></span>
这很容易,但无法弄清楚。
此致
答案 0 :(得分:2)
您正在连接字符串而不是总和数字。请将值转换为数字,它完美无缺。请参阅评论的行:
var x = document.getElementById("x");
var y = document.getElementById("y");
var d = document.getElementById("d");
var xstored = x.getAttribute("data-in");
var ystored = y.getAttribute("data-in");
setInterval(function(){
if( x == document.activeElement ){
var temp = x.value;
if( xstored != temp ){
xstored = temp;
x.setAttribute("data-in",temp);
calculate();
}
}
if( y == document.activeElement ){
var temp = y.value;
if( ystored != temp ){
ystored = temp;
y.setAttribute("data-in",temp);
calculate();
}
}
},50);
function calculate(){
//here you need to convert values to numbers
var total = Number(x.value) + Number(y.value);
if( total >= 50 ){
d.innerHTML = ((x.value * 1.00) + (y.value * 2.00)) / 2;
}
else{
d.innerHTML = (x.value * 1.00) + (y.value * 2.00);
}
}
x.onblur = calculate;
calculate();
#d{
text-indent:20px;
}
<h3>Calculate</h3>
item1 <input id="x" data-in="" type="number" /><br>
<br>
item2 <input id="y" data-in="" type="number" /><br>
<br>
Please Pay and amount of <span id="d"></span>
解释是你连接这个:
var one = "10";
var two = "15";
var result = one + two ; // result string "1015"
但是如果你换成数字,总和是完美的
var one = "10";
var two = "15";
var result = Number(one) + Number(two) ; // result int 25
答案 1 :(得分:1)
这是非常直接和简单的
您的代码是正确的,除了一件事,您没有使用 parseInt ,
目前您连接值而不是添加,
所以只需替换此代码
var total = x.value + y.value;
这一个
var total = parseInt(x.value) + parseInt(y.value);
那就是:)