jquery - 按钮只是用户顶部

时间:2017-07-13 14:58:32

标签: jquery

我有删除按钮。通过单击它,我运行ajax代码,从数据库中删除数据。

当我点击按钮时,用户屏幕跳转到页面顶部。 我该如何防止这种情况发生?

我希望用户在框被删除时留在同一个地方......

HTML

<article class="row fadeSec" id="60">
    <a href="#" class="delBtn" data-type="itin-comment" data-alert="true"><i class="fa fa-trash pull-right"></i></a>
</article>

<article class="row fadeSec" id="61">
    <a href="#" class="delBtn" data-type="itin-comment" data-alert="true"><i class="fa fa-trash pull-right"></i></a>
</article>

JQUERY

$(document).on("click", ".delBtn", function(){

    var element = $(this);
    var deleteID = element.closest('.fadeSec').attr("id");
    var type = element.attr("data-type");
    var alertMsg = element.attr("data-alert");

    if (alertDeleteComment(deleteID))
    {
        var info = 'deleteID=' + deleteID + "&type=" + type;          
    //  alert(info);
        $.ajax({
          type: 'POST',
          url: 'ajax/ajax_delete_id.php',
          data: info,
          async: false,
          success: function (data) {
              if (data != "false") {
                  element.closest('.fadeSec').animate({ opacity: "hide" }, "slow");
              }
          }
          });
    }

});

1 个答案:

答案 0 :(得分:2)

您应该阻止此的默认行为:

$(document).on("click", ".delBtn", function(e){
e.preventDefault(); // <---- THIS IS THE PREVENTION

    var element = $(this);
    var deleteID = element.closest('.fadeSec').attr("id");
    var type = element.attr("data-type");
    var alertMsg = element.attr("data-alert");

    if (alertDeleteComment(deleteID))
    {
        var info = 'deleteID=' + deleteID + "&type=" + type;          
    //  alert(info);
        $.ajax({
          type: 'POST',
          url: 'ajax/ajax_delete_id.php',
          data: info,
          async: false,
          success: function (data) {
              if (data != "false") {
                  element.closest('.fadeSec').animate({ opacity: "hide" }, "slow");
              }
          }
          });
    }