首页 文章

onclick取消按钮仍然调用ajax

提问于
浏览
0

按钮onclick看起来像这样 onclick="return confirm('Are you sure to delete this item?')" . 即使点击了取消,该帖子仍然被删除 .

然后在jquery中 .

$(document).ready(function(){
    $('.btn').click(function(event){
    event.preventDefault(); 
        $a = $(this).text().trim();
        if ($a == "Delete") 
        {
            var postid = $(this).next('.postid').val();
            $(this).closest(".todo-content").fadeOut('slow');
            $.ajax({
                type: "POST",
                url: BASE_URL+'classes/deletepost',
                dataType: 'json',
                data: {postid: postid},
                async: false,
                success: function( data ) {
              },
              error: function(xhr, status, error) {
                  // check status && error
            }
      });
        }
    });
});

如果单击确认中的取消,是否有取消对ajax的调用?

5 回答

  • 0

    完全删除 onclick ,并在函数中构造代码:

    function deleteItem() {
        if (confirm('Are you sure to delete this item?')) {
            // code to delete...
        }
    }
    
    $(document).ready(function(){
        $('.btn').click(function(event){
            deleteItem();
        });
    });
    
  • 0

    我想,你可以像这样使用它

    在{event.preventDefault();}之后的Ajax函数中,这行添加如下

    如果(!确认(“你确定”))返回;

  • 0

    为什么不简单地从2个地方的事件转移到1个?将确认移出HTML并将其放入您的javascript中,如下所示:

    $(document).ready(function(){
        $('.btn').click(function(event){
           if (!confirm('Are you sure to delete this item?'))
             return;
    
           event.preventDefault(); 
           /* code to delete here */
        });
    });
    
  • 3

    修改您的代码以在您的javascript中包含确认而不是内联 .

    $('.btn').click(function(event){
    if(!confirm('Are you sure to delete this item?'))
    return;
        event.preventDefault(); 
    ...
    ...
    ...
    
  • 0

    如果单击确认中的取消,是否有取消对ajax的调用?

    是的,这是可能的 . 您可以将 confirm 的结果放在变量中:

    onclick="doDelete=confirm('Are you sure to delete this item?');"
    

    在jQuery代码中,您可以检查变量的值:

    $(document).ready(function(){
      $('.btn').click(function(event){
        event.preventDefault();
        if (doDelete) {
          ...
        }
      });
    });
    

    但是,有可能不是最好的解决方案 . 最明显的解决方案是在jQuery代码中执行 confirm 调用 .

相关问题