简体   繁体   中英

Remove a specific DIV in a row by its ID

I am using Django and have several Bootstrap cards on my page like the structure below, and I am trying to remove one div on click (X on my <a> )

<row>
  <col-sm-3 id="{{ topic.pk }}">
    <card>
      <...><a href="" class="remove" data-id="{{ topic.pk }}">X</a></> #ID here is 1
    </>
  </>
  <col-sm-3 id="{{ topic.pk }}">
    <card>
      <...><a href="" class="remove" data-id="{{ topic.pk }}">X</a></> #ID here is 2
    </>
  </>
</>
$(function(){
  $('a.remove').on('click', function(e) {
    e.preventDefault();
    var $this = $(this);
    var id = $this.data('id');
    $.get('/messages/delete/'+id, {}, function(response) {
      $this.parent().fadeOut(300, function(){
        $(this).remove();
      });
    });
  });
});

The on click doesn't work. Debugging the code:

127.0.0.1:8000/messages/delete/1 404 NOT FOUND

I understand, the "a" has a connection to my function. What I don't understand, whats the purpose of

$.get('/messages/delete/'+id, {}, function(response)?

I just want the Card-Div to be removed. How can I change my code to make it work? Any input appreciated.

Extending my comment.

This part:

$.get('/messages/delete/'+id, {}, function(response) { ... });

is an AJAX call (that also uses the GET HTTP method - and it should use either POST or DELETE) that sends a request to the specified route. One could guess that it's connected to a delete method, to remove a row with specified ID from a database.

Your error comes up, because you don't have that route set up.

This part:

$this.parent().fadeOut(300, function(){$(this).remove()

is the one that actually removes the HTML element from the page. In your current code it's called in a callback function from the AJAX request (that never succeeds), therefore it never fires.

If you only want to remove the card element from the html, you should go with:

$(function(){
  $('a.remove').on('click', function(e) {
    e.preventDefault();
    $(this).closest('card').remove();
  });
});

If you actually want to remove a row from a table in your database that would require you setting up a route and a method in the backend (Django in your case), and then removing it in the frontend after a successful request.

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