我有一些使用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!");
}
}
})
})
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。