首页 > 解决方案 > 使用 $(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.

标签: jquery

解决方案


因为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){}
    });
});

推荐阅读