(根据网上商店)
我想添加一个删除函数,在其中删除使用 ajax 和 jquery 插入的整个条目,但它没有按我想要的方式工作。
使用以下代码:
$('#div').on('click', '.orderd', function() {
$(this).remove();
});
function UpdateTotal() {
ToAddHTML = '<h1>Shopping cart</h1>';
Totalprice = 0;
for (var i = 0; i < orders.length ; i++) {
var zoekresultaat = SubMenuItems.filter(function(v) {
return v.submenu_id === orders[i];
})[0];
Totalprice += parseFloat(searched.price);
ToAddHTML += '';
}
ToAddHTML += ''
$("#totalen").html(ToAddHTML);
}
这有效,但是当我console.log数组“orderd items”时,它仍然重复ordered items。 因此,当我单击其他项目时,“刚刚删除”的订单会再次弹出。
很难解释我当前的问题,但我希望我已经了解了足够的信息!如有任何疑问,请提问!我会更新我的问题!
最佳答案
您应该从数组中删除有序 ID,并在删除项目时重新计算您的“篮子”。
// =======================================================================
// ! Functie maken die de totalen-lijst bijwerkt
// =======================================================================
function WerkTotalenBij() {
ToeTeVoegenHTML = '<h1>Winkelmandje</h1>';
Totaalprijs = 0;
for (var i = 0; i < Bestellingen.length ; i++) {
var zoekresultaat = SubMenuItems.filter(function(v) {
return v.submenu_id === Bestellingen[i];
})[0];
Totaalprijs += parseFloat(zoekresultaat.price);
// here I put a "data-itemid" attribute to keep a raw reference to the item id
// this ID can be retrieved in the remove handler
ToeTeVoegenHTML += '<div class=besteld id=nummer'+Bestellingen[i]+' data-itemid="'+Bestellingen[i]+'">'+'€'+zoekresultaat.price+' '+zoekresultaat.title+'</br>(verwijder)</div><hr>';
}
ToeTeVoegenHTML += '<br/>Totale prijs per persoon :<br/> € '+Totaalprijs+'<br/>Minimaal 10 personen<br/> Aantal personen:<input type=text width="10px" /><input type="button" value="Ik ben klaar!">';
$("#totalen").html(ToeTeVoegenHTML);
}
$('#totalen').on('click', '.besteld', function() {
var itemID = $(this).data("itemid");
// remove the item ID from the array
var index = Bestellingen.indexOf(itemID);
if (index > -1) {
Bestellingen.splice(index, 1);
}
$(this).remove();
// recalculate orders
WerkTotalenBij();
});
但无论如何,这是典型的工作,您应该使用例如 knockout.js libaray,您可以在其中将 DOM 元素直接绑定(bind)到您的数据,并且足以操纵您的数据,GUI 将自动反射(reflect)更改。相信我,值得学习,你不会后悔的。
关于javascript - 删除jquery创建的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22749603/