单击时删除其中一个添加的行

我想只删除我按下的特定.delete的行。 我怎样才能在jQuery中指定它。 现在它正在删除所有的p,因为我选择了它作为值,但我无法弄清楚如何使其特定于每个追加行。

HTML

 

jQuery的

 $(document).ready(function() { var totalPrice = 0; $('.food').click(function() { var $frm = $(this).parent(); var toAdd = $frm.children(".productInput").val(); var addPrice = $frm.children(".priceInput").val(); var addAmount = $frm.children(".amountInput").val(); var div = $("
"); div.append("

" + addAmount + "

", "

" + toAdd + "

", "

" + addPrice + "

", "

" + "X" + "

"); $frm.parent().children(".messages").append(div); totalPrice += addAmount * addPrice; $(".totalPrice").text("Total Price: $" + totalPrice); }); }); $(document).on('click', '.delete', function() { $('p').remove() });

你应该删除所有p的父div,如:

 // This is delegated event as the HTML element is added dynamically $(document).on('click', '.delete', function() { $(this).closest("div").remove(); // .closest will traverse upwards to find the matched element that is div }); 

注意 :您需要使用事件委派,因为HTML元素是动态添加的。 在此了解更多信息。

如果要删除正在添加的元素,您只需要在函数中使用$(this)来引用触发调用的元素:

 // When an element with the delete class is clicked $(document).on('click', '.delete', function() { // Remove the closest 
above the element that was clicked $(this).closest('div').remove(); });

如果你想更新价格……

当您删除元素时,您可能还需要考虑更新定价,您可以通过阅读最后一个元素并减去它来做到:

 $(document).on('click', '.delete', function() { // Get the previous element which contains your price var priceToSubtract = parseInt($(this).prev().text()); // Subtract the price totalPrice -= priceToSubtract; // Update your price $(".totalPrice").text("Total Price: $" + totalPrice); $(this).closest('div').remove(); }); 

这将要求您在$(document).ready()块之外totalPrice变量的范围,如下所示: