我想只删除我按下的特定.delete的行。我怎样才能在jQuery中指定它。现在它删除了所有的p,因为我选择了它作为值,但我无法弄清楚如何使其特定于每个追加行。
HTML
<div id="menu">
<h3>Shopping list</h3>
<div class="line">
<p class="title">Amount</p>
<p class="title">Product</p>
<p class="title">Price</p>
<div>
<input class='amountInput' type='number' name='quantity' min='0' max='1000' step='1'>
<input class='productInput' type="text" name="message" value="">
<input class='priceInput' type='number' name='quantity' min='0' max='1000000' step='0.01'>
<button class="food">Add</button>
</div>
<div class="messages">
</div>
</div>
</div>
<div class="totalPrice">
</div>
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>");
div.append("<p>" + addAmount + "</p>", "<p id='product'> " + toAdd + " </p>", "<p>" + addPrice + "</p>", "<p class='delete'>" + "X" + "</p>");
$frm.parent().children(".messages").append(div);
totalPrice += addAmount * addPrice;
$(".totalPrice").text("Total Price: $" + totalPrice);
});
});
$(document).on('click', '.delete', function() {
$('p').remove()
});
答案 0 :(得分:1)
如果要删除正在添加的元素,您只需要在函数中使用$(this)
来引用触发调用的元素:
// When an element with the delete class is clicked
$(document).on('click', '.delete', function() {
// Remove the closest <div> 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();
});
这将要求您将totalPrice
变量放在$(document).ready()
块之外,如下所示:
<script>
var totalPrice = 0;
$(document).ready(function() {
// Your code here
});
</script>
答案 1 :(得分:0)
您应该删除所有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元素是动态添加的。详细了解here。