我正在做一个网上商店,顾客可以通过下拉列表选择购买的商品数量。每件商品都有一个积分值,我通过jQuery (onChange
事件)计算他们购买的总金额:
function showPoints(itemPointValue, ddlAmount){
var customerPoints = parseInt($('p#points').html());
currentPoints = customerPoints - (ddlAmount * itemPointValue);
$('p#points').html(currentPoints);
}//showPoints
这里唯一的问题是,如果他们将数量从5改为4,那么另外4*点数就会从他们的“总点数”中去掉。他们的总分最终变得完全不准确,甚至可能低于0。我想使用jquery.data
来设置一个"oldValue“变量,但是IE不支持这个。有什么建议吗?
发布于 2012-11-23 20:14:54
我通过使用下拉列表中的两个事件解决了这个问题。onClick保存旧数据,使用jquery.data和onChange对照新值检查旧值。如果新值比旧值小,我就相应地调整总分。
HTML:
<select name="dropdown onClick="saveOld(this.value, this.name)" onchange="showPoints(points, this.value,this.name)">
JS/Jquery
function showPoints(pointCategory, ddlAmount, name){
old = jQuery.data(document.body,name);
var Points = parseInt($('p#points').html());
if(old > ddlAmount){
diff = old - ddlAmount;
currentPoints = Points + (diff * pointCategory);
}else{
currentPoints = Points - (ddlAmount * pointCategory);
}
$('p#points').html(currentPoints);
}//showPoints
function saveOld(oldAmount, name){
$(document.body).data(name,oldAmount);
}//saveOld
感谢你们所有人的回答!
发布于 2012-11-23 18:47:52
如上所述,您可以将之前的值存储在自定义属性中,并且可以使用focus事件来设置旧值,下面这几行中的内容应该是有效的:
$('p#points').on('focus', function () {
$(this).attr('old-value', $(this).val();
});
发布于 2012-11-23 17:05:10
为什么不在任何时候任何下拉列表发生变化时重新计算总点数成本,并通过从customerPoints中减去新的总点数来重新计算currentPoints?在我看来,这似乎是一种比加减值更干净的解决方案
https://stackoverflow.com/questions/13525688
复制相似问题