我有锚标签,这是我的HTML

<tr data-id="5" class="rowshow">
    <td>0</td>
    <td>
        <input name="ctl06" type="text" value="قرمه سبزی" />
    </td>
    <td>
        <input name="ctl08" type="text" value="1000" />
    </td>
    <td><a Class="deleteBtn">X</a>
    </td>
</tr>
<tr data-id="6" class="rowshow">
    <td>1</td>
    <td>
        <input name="ctl14" type="text" value="قرمه سبزی" />
    </td>
    <td>
        <input name="ctl16" type="text" value="1000" />
    </td>
    <td><a Class="deleteBtn">X</a>
    </td>
</tr>

我想在点击“a”标签后删除ajax成功而不刷新我的页面
这是我的剧本
$(".deleteBtn").click(function () {
    var id = $(this).closest(".rowshow").data("id");
    $.ajax({
        type: "POST",
        url: "EditFood.aspx/delete",
        data: "{'id':" + id + "}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            $(this).parent(".rowshow").remove();
        }
    });
});

最佳答案

两个问题:
在ajax中无法访问$(this),因为this指的是ajax调用的jqXHR对象,而不是单击的按钮。在ajax调用之前缓存对象,然后使用它。
您需要将.parent(".rowshow")更改为.closest(".rowshow")parent只查看直接父级,不扫描。
所以:

$(".deleteBtn").click(function (event) {

    event.preventDefault();

    var id = $(this).closest(".rowshow").data("id");
    var $this = $(this);
    $.ajax({
        type: "POST",
        url: "EditFood.aspx/delete",
        data: "{'id':" + id + "}",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function () {
            $this.closest(".rowshow").remove();
        }
    });
});

另外,添加event.preventDefault()以避免默认的a操作。
使用setTimeout模拟ajax调用的示例:
$(".deleteBtn").click(function(event) {

  event.preventDefault();

  var id = $(this).closest(".rowshow").data("id");
  var $this = $(this);
  setTimeout(function() {
    $this.closest(".rowshow").remove();
  }, 500);
});

<table>
  <tbody>
    <tr data-id="5" class="rowshow">
      <td>0</td>
      <td>
        <input name="ctl06" type="text" value="قرمه سبزی" />
      </td>
      <td>
        <input name="ctl08" type="text" value="1000" />
      </td>
      <td><a Class="deleteBtn">X</a>
      </td>
    </tr>
    <tr data-id="6" class="rowshow">
      <td>1</td>
      <td>
        <input name="ctl14" type="text" value="قرمه سبزی" />
      </td>
      <td>
        <input name="ctl16" type="text" value="1000" />
      </td>
      <td><a Class="deleteBtn">X</a>
      </td>
    </tr>
  </tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

09-30 16:07
查看更多