简体   繁体   中英

.remove() not working with ajax on success function

I have some html divs that are generated using jinja2 with this:

{% for student in students %}
<div class="item" id="{{ student.id }}_div">
   <div class="right floated content">
      <div class="negative ui button compact remove_from_class" id="{{ student.id }}">Remove from Class</div>
   </div>
   <i class="large user icon middle aligned icon"></i>
   <div class="content">
      <div class="header">
         <h3><u>{{ student.get_full_name }}</u></h3>
      </div>
      <div class="description">{{ student.email }}</div>
   </div>
</div>
{% endfor %}

This is the script I have for it which gets the parent divs id, and then tries to remove it using .remove().

$(".remove_from_class").each(function () {
$(this).on("click", function () {
    var id = this.id;
    var url = window.location.pathname.split('/');
    var set_id = url.pop() || url.pop()


    $.ajax({
        method: 'POST',
        url: '/ajax/delete_from_class/',
        data: {
            'id': id,
            'set_id': set_id,
        },
        dataType: 'json',
        success: function (data) {
            if (data.success == true) {
                var div_id = id + "_div";
                var parent_div = $(div_id);
                parent_div.remove();

            } else {
                alert("Student wasn't removed!");
            }

        }
    })
})
})

However the div isnt being removed, even though the success popup appears.

Thanks for any help!

You need to use # to use id as a selector.

var div_id = "#"+id + "_div"; // Use # here
var parent_div = $(div_id);
parent_div.remove();

Or the better approach I would suggest here is to store div inside .click in some variable and then later use that.

$(".remove_from_class").each(function () {
$(this).on("click", function () {
    var $parentDiv = $(this).closest(".item"); // Save it here
    var id = this.id;
    var url = window.location.pathname.split('/');
    var set_id = url.pop() || url.pop()


    $.ajax({
        method: 'POST',
        url: '/ajax/delete_from_class/',
        data: {
            'id': id,
            'set_id': set_id,
        },
        dataType: 'json',
        success: function (data) {
            if (data.success == true) {
                $parentDiv.remove(); // And remvoe it here

            } else {
                alert("Student wasn't removed!");
            }

        }
    })
})
})

请尝试这样

$('#'+ id +'_div').remove();

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