单击时删除其中一个添加的行 [英] Remove one of the added lines on click

查看:66
本文介绍了单击时删除其中一个添加的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to only remove the line of the specific .delete that I press. How can I specify that in jQuery. Now it's removing all the p since I've chosen that as the value but I can't figure out how to make it specific for each line of append.

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()


 });


推荐答案

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

You should remove the parent div of the all the p, like:

// 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元素时使用事件委派动态。了解更多信息此处

Note: You need to use event delegation as the HTML elements are added dynamically. Learn more about it here.

这篇关于单击时删除其中一个添加的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆