我正在尋找一個整潔的方式做以下,但有腦部凍結:選擇最高的組合
用戶可以添加(並隨後刪除)類型的購物籃。 對於每一個添加或刪除,我需要看看是否有更高層次的類型可以建議。最高類型是優選的(音符它具有相同的價格作爲倒數第二個類型,但是應該B6優於B5)
實例:
2 x type1 (100+100) -> 1 x type2
type1 + type3 (100+300) -> 1 x type4
type3 + type4 (300+400) -> 1 x type6 + 1 x type2
1 type6 + 1 type2 + 1 type1 -> 1 x type6 + 1 x type3
等。
因此,如果總數爲0,只需添加任何被點擊。 如果不是,請查看總數加上新點擊是否可以從頂部開始以更好的組合方式解決。如果用戶拒絕該建議,請忽略該添加。
到目前爲止的代碼(標籤爲jQuery,因爲代碼使用它 - 地圖和過濾器是受歡迎的) 我還沒有發佈我的recalc嘗試,因爲我想避免X/Y problem。
var types= {
b1: {price:100,quantity:0},
b2: {price:200,quantity:0},
b3: {price:300,quantity:0},
b4: {price:400,quantity:0},
b5: {price:500,quantity:0},
b6: {price:500,quantity:0}
}
function getTotal() {
var total = 0;
$.each(types,function(typeId,type) {
total+=type.quantity*type.price;
});
return total
}
$(function() {
var cont = $("#container");
$.each(types,function(typeId,type) {
$('<button class="add" id="'+typeId+'add">Add to '+typeId+'<button><span id="'+typeId+'val">0</button><button class="remove" id="'+typeId+'remove">Remove from '+typeId+'</button><span id="'+typeId+'total">0</span><br/>').appendTo(cont);
});
$(".add").on("click",function() {
var id = this.id.replace("add",""),type=types[id];
type.quantity++;
var subTotal = type.quantity*type.price;
$("#"+id+"val").text(type.quantity);
$("#"+id+"total").text(subTotal);
$("#total").text(getTotal());
});
$(".remove").on("click",function() {
var id = this.id.replace("remove",""),type=types[id];
if (type.quantity>0) type.quantity--;
var subTotal = type.quantity*type.price;
$("#"+id+"val").text(type.quantity);
$("#"+id+"total").text(subTotal);
$("#total").text(getTotal());
});
});
因此,如果用戶點擊'添加b1'兩次,你想結果顯示0爲b1和1爲b2? – Malk
B6和B5的價格都是500?也許b6應該有600的價格(可能是你的錯字)?如果不是我們選擇什麼呢? – ssBarBee
不唉不錯。 B6首選。 – mplungjan