简体   繁体   中英

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.

I created a div <div id="records"> </div> which I keep appending things to using $("#records").prepend(new_record) using jQuery.

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 .

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. 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. This snippet finds the parent div of the button that is clicked and removes it.

$('#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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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