简体   繁体   English

使用jQuery单击按钮时在div中删除一行

[英]Delete a row in div when click the button using jQuery

在此处输入图片说明

Shown in the picture above, I am trying to delete the row when the x button is clicked. 如上图所示,单击x按钮时,我试图删除该行。

I created a div <div id="records"> </div> which I keep appending things to using $("#records").prepend(new_record) using jQuery. 我创建了一个div <div id="records"> </div> ,它不断使用jQuery将内容附加到$("#records").prepend(new_record)中。

The way I implemented the row is: 我实现该行的方式是:

var new_record = username + " " + $("#client-name").val() + $("#reams").val()+ " "+ "<button id='btn-sm'> x </button>"

where I just append every part including the button to the variable new_record . 在这里,我只是将包括按钮的每个部分附加到变量new_record

However, I am stuck on how to delete this specific row once I click the button, since each button is identical to others. 但是,单击按钮后,我将停留在如何删除此特定行上,因为每个按钮都与其他按钮相同。 Is there a better way to implement this? 有没有更好的方法来实现这一目标?

You'll want a way to identify the entire row so I would wrap each entry in a div or some other element. 您将需要一种识别整个行的方法,以便将每个条目包装在div或其他元素中。 Then, since the elements are added dynamically, you'll need to use delegated event handling - sensing a click in a parent element and then checking if the real source is from a specific type of child element - which is simple with jQuery. 然后,由于元素是动态添加的,因此您需要使用委托事件处理-感测父元素中的单击,然后检查真正的来源是否来自特定类型的子元素-jQuery很简单。 This snippet finds the parent div of the button that is clicked and removes it. 此代码段查找被单击按钮的父div并将其删除。

$('#records').on('click', 'button', function() {
  $(this).parent('div').remove(); 
});

 var username = "test"; var new_record = "<div>" + username + " " + $("#client-name").val() + $("#reams").val() + " " + "<button id='btn-sm'> x </button></div>"; $("#records").prepend(new_record); $("#records").prepend(new_record); $("#records").prepend(new_record); $('#records').on('click', 'button', function() { $(this).parent('div').remove(); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="records"> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM