我意识到这可能已经以一种或另一种方式得到了回答,同时我将继续努力寻找解决方案。我只是希望对处理这个问题的最佳方法有一些想法。
我有一个购物车。我的网站将许多商店链接在一起。我的网站是基于重量而不是数量。我的购物车最大容量为 28 克。
如果用户在购物车中有物品,他们决定增加重量。旧项目被新项目替换。
在此过程中,旧物品重量被添加到新物品重量中,然后添加到购物车当前重量。我需要从这个过程中排除旧物品的重量,只比较新物品和购物车中的其他物品。
我找到了一个可以调用重复项并获得权重结果的函数。
我从总数中减去金额,一切都很好!
错误的!我发现获取重复项目重量的函数,如果没有重复项目,将返回 false。现在该函数位于另一个基于返回真或假的函数内。True 表示该项目已“添加”,false 表示该项目“未添加”。所以当我的购物车是空的或者没有重复时,整个函数过早地结束了。
我之所以发布这个只是因为我注意到有很多方法可以实现这一点,而且其中很多解决方案已经有 5 年的历史了。
现在这里是魔法发生的地方
<script>
simpleCart.bind('beforeAdd', function (item) {
var existItem = simpleCart.has(item).get('weight');
var multi_item = simpleCart.quantity();
var cartweight = simpleCart.weight();
var shopid = simpleCart.sid();
var newweight = $( "div.item_weight" ).text();
var itemid = $( "div.item_id" ).text();
var totalweight = parseInt(cartweight) + parseInt(newweight) - parseInt(existItem);
if(shopid != null && shopid != <?=$shopid?> ){
$( "#pop_fail_store" ).popup( "open" )
return false;
}else if (parseInt(totalweight)>=29){
$( "#pop_fail_weight" ).popup( "open" )
return false;
}else if (simpleCart.has(item)){
$( "#pop_update" ).popup( "open" )
return true;
}else {
return true;
}
});
//SUCCESS
simpleCart.bind( "afterAdd" , function( item ){
$( "#pop_success" ).popup( "open" )
});
</script>
当没有项目时,这将返回 false,并提前终止该函数。
var existItem = simpleCart.has(item).get('weight');
这些是代表 HAS EQUALS 和 GET 的函数
has: function (item) {
var match = false;
simpleCart.each(function (testItem) {
if (testItem.equals(item)) {
match = testItem;
}
});
return match;
}
me.equals = function (item) {
for( var label in _data ){
if (Object.prototype.hasOwnProperty.call(_data, label)) {
if (label !== 'quantity' && label !== 'id' && label !== 'price' && label !== 'weight') {
if (item.get(label) !== _data[label]) {
return false;
}
}
}
}
return true;
};
me.get = function (name, skipPrototypes) {
var usePrototypes = !skipPrototypes;
if (isUndefined(name)) {
return name;
}
// return the value in order of the data object and then the prototype
return isFunction(_data[name]) ? _data[name].call(me) :
!isUndefined(_data[name]) ? _data[name] :
isFunction(me[name]) && usePrototypes ? me[name].call(me) :
!isUndefined(me[name]) && usePrototypes ? me[name] :
_data[name];
};
我不能在不弄乱其他函数的情况下更改 get、has 或 equals 函数。我只需要它返回的值。
我的第一个计划是将其移出“添加前”函数并将其保存为就绪函数内的全局变量,然后在启动“添加前”函数后调用它?这是最好的方法吗?
或者
阿贾克斯...
或者
做一个新功能?
或者我可以添加另一个 if 语句吗?
选择的力量并不总是最好的。我敢肯定,有一个简单的答案让我眼前一亮。
也许有人可以告诉我 2017 年最有效的方法。
我网站上的一个页面点击这里
提前致谢!