jquery - 使用 $(this) 时,$(document).on() 在 ajax 之后不起作用
问题描述
我目前有这个代码
$(document).on("click", ".element", function(e){
e.preventDefault();
$.ajax({
type:'POST',
url: "ajax/ajax-submit.php",
success:function(data){
if(data == "success") {
console.log("deleted upload");
$(this).parents(".parent-element").remove();
}
},error: function(data){}
});
});
这是HTML
<div class="parent-element">
<div class="container">
<button class="element">Remove Parent</button>
</div>
</div>
在ajax成功后这$(this)
不起作用。
我想要的是删除它的父.element
级.parent-element
。
注意*:这
.element
是在.parent-element
.
解决方案
因为this
现在属于success
方法,所以添加变量oThis
然后在success
方法中使用删除
$(document).on("click", ".element", function(e){
var oThis = this;
e.preventDefault();
$.ajax({
type:'POST',
url: "ajax/ajax-submit.php",
success:function(data){
if(data == "success") {
console.log("deleted upload");
$(oThis).parents(".parent-element").remove();
}
},error: function(data){}
});
});
推荐阅读
- scala - 用 Scala API 调用替换 Spark SQL
- javascript - 如何从数组中的每个数字创建一个数组?
- javascript - 在 javascript forEach 函数中访问“this”
- react-native - 反应导航错误(未定义不是对象(评估'Component.router.getStateForAction'))
- javascript - 我有javascript qustion,我想知道如何忽略正则表达式中的破折号,例如如果我输入蜘蛛侠,我希望它等于蜘蛛侠
- python - 当输入字符串/对象格式不正确时,如何将对象或字符串转换为时间格式,即所有行都不存在 %H
- ansible - Ansible playbook 通过终端执行时成功运行,但在 Gitlab CI/CD 管道中失败
- python - 在为图像着色准备数据时,colab 中的会话崩溃
- java - 将多个数据库与 Spring Data JPA 一起使用时,不会发生名为“ConfigurationClassPostProcessor.importRegistry”的 bean 异常
- security - 是否防篡改?