[英].remove() not working with ajax on success function
我有一些使用jinja2生成的html div:
{% 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 %}
這是我擁有的腳本,它獲取父divs id,然后嘗試使用.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!");
}
}
})
})
})
但是,即使出現成功彈出窗口,div也不會被刪除。
謝謝你的幫助!
您需要使用#
來使用id
作為選擇器。
var div_id = "#"+id + "_div"; // Use # here
var parent_div = $(div_id);
parent_div.remove();
或者我建議的更好的方法是將div
存儲在.click
中的某個變量中,然后再使用它。
$(".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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.