Javascript 单击删除其中一个添加的行
我只想删除特定的行。删除我按的行。如何在jQuery中指定它。现在它删除了所有的p,因为我已经选择了p作为值,但是我不知道如何使它特定于append的每一行 HTMLJavascript 单击删除其中一个添加的行,javascript,jquery,Javascript,Jquery,我只想删除特定的行。删除我按的行。如何在jQuery中指定它。现在它删除了所有的p,因为我已经选择了p作为值,但是我不知道如何使它特定于append的每一行 HTML 购物清单 金额 产品 价格 添加 jQuery $(document).ready(function() { var totalPrice = 0; $('.food').click(function() { var $frm = $(this).parent(); var toAdd = $frm.chi
购物清单
金额
产品
价格
添加
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()
});
$(文档).ready(函数(){
var totalPrice=0;
$('.food')。单击(函数(){
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);
总价+=addAmount*addPrice;
$(“.totalPrice”).text(“总价:$”+totalPrice);
});
});
$(文档)。在('单击','删除',函数()上){
$('p').remove()
});
如果要删除正在添加的元素,只需在函数中使用$(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();
});
这将要求您在$(文档).ready()
块之外确定totalPrice
变量的范围,如下所示:
<script>
var totalPrice = 0;
$(document).ready(function() {
// Your code here
});
</script>
var totalPrice=0;
$(文档).ready(函数(){
//你的代码在这里
});
您应该删除所有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元素时,需要使用事件委派。了解更多信息。你到底想删除什么?当我单击时。我添加addAmount、toAdd和一个X。当我单击p class=“delete”时,我希望它删除与特定字母X一起添加的addAmount和toAdd。检查下面的答案。这只会删除我正在单击的一个,我希望它删除与X.in click事件一起添加的另外两个,使用:
$(this).closest(“div”).remove()代码>这将删除所有p标记。我在再次检查问题时刚刚注意到此问题。我已经相应地更新了。此外,您可能需要考虑在删除元素时更新定价。
<script>
var totalPrice = 0;
$(document).ready(function() {
// Your code here
});
</script>
// 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
});