jquery 函数不会在 get 请求完成时隐藏元素



我正在尝试使用 jQuery 向服务器发送 get 请求,我相信它运行正常,因为正在删除记录,但我想在请求成功完成后隐藏单击的元素。

下面是一个示例 html 代码段,它是通过jinja2模板生成的:

{% for class in classes %}
<tr>
<th scope="row">{{ class[0] }}</th>
<td>{{ class[1] }}</td>
<td>{{ class[2] }}</td>
<td><a href="/classes/{{ class[0] }}">{{ class[4] }}</a></td>
<td class=>
<svg class="bi bi-trash" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" id="{{ class[0] }}" xmlns="http://www.w3.org/2000/svg">
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
<path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
</svg>
</td>
</tr>
{% endfor %}

svg标签中包含的图片是一个垃圾桶的图片,我有一个jquery脚本,它向python服务器发起GET请求,以删除带有id值的记录,如下所示:

<script>
$(document).ready(function(){
$("svg").click(function(){
var id = $(this).attr('id');
decision = window.confirm("Are you sure you want to delete this class?");
if (decision === true) {
var url = '/classes/' + id + '/delete';
jQuery.get(url, function(){
console.log("It worked.");
$(this).closest('tr').hide();
});
}
});
});
</script>

这个想法是,如果您单击该图标,系统会询问您是否要删除相应的记录,如果您单击"确定",则会启动 get 请求。

截至目前,发生这种情况时,记录将被删除,但除非我刷新它,否则页面上的视图不会更改。 假设这是正确的行为,我想只隐藏包含图标的行,这是 jquery 脚本背后的想法,但该行没有被隐藏,我不确定我的代码在哪里不正确。

很想知道我做错了什么。

您需要使用箭头函数保存对外部this的引用(jQuery.get的回调函数内部的this与事件侦听器函数内的this值不同(。

$("svg").click(function(){
var id = $(this).attr('id');
decision = window.confirm("Are you sure you want to delete this class?");
if (decision === true) {
var url = '/classes/' + id + '/delete';
jQuery.get(url, ()=>{
console.log("It worked.");
$(this).closest('tr').hide();
});
}
});
});

如果你想使用this来访问元素,它应该引用外部函数。 你只需要$(this).closest('tr').hide()移动到 jquery 回调之外

$("svg").click(function(){
var id = $(this).attr('id');
decision = window.confirm("Are you sure you want to delete this class?");
if (decision === true) {
$(this).closest('tr').hide()
var url = '/classes/' + id + '/delete';
jQuery.get(url, function(){
console.log("It worked.");
;
});
}
});
});

试试这个,希望对你有所帮助

$("svg").click(function() {
// Var definition
var $this = $(this);
var id = $this.attr('id');
// Get confirmation
decision = window.confirm("Are you sure you want to delete this class?");
// Check the decision
if (decision) {
var url = '/classes/' + id + '/delete';
// Send GET request
$.get(url, function() {
// You can hide or remove the table row
$this.closest('tr').hide();
});
}
});

最新更新