转换为Bootbox确认

7
以下代码在点击“删除用户”链接时弹出确认窗口:
<a href="delete_user.php?id=123" onclick="return confirm('Are you sure?');">Delete user</a>

在这种情况下,当点击“确定”按钮时,将执行链接delete_user.php?id=123。当点击“取消”按钮时,什么也不会发生。
我希望使用Bootbox实现同样的功能。
   <a class="alert" href="list_users.php?id=123">Delete user</a>

    <script src="bootbox.min.js"></script>
        <script>
        $(document).on("click", ".alert", function(e) {
            e.preventDefault();

        bootbox.confirm("Are you sure?", function(result) {

            if (result) {
               // What to do here?
            } else {
               // What to do here?
            }               
        });

        });
    </script>

在 if(result) 和 else 语句下应该做什么?


如果(result)document.location.href = this.attr('href');。不需要else。 - Julian H. Lam
当我使用this.attr('href')时,出现TypeError: this.attr不是一个函数。当我改为$(this).attr('href')时,出现Undefined。有什么想法吗? - Oualid
嗯...如果你尝试使用this.href会怎样? - Julian H. Lam
1
我认为@JulianH.Lam的解决方案存在作用域问题。$(this)作为链接在bootbox.confirm()函数中不存在。我曾经遇到过类似的问题。我的解决方案是创建一个隐藏按钮和一个可见按钮,然后在if(result){}调用$("#hiddenbuttonID).click()。 - RandomWebGuy
我找到了如何解决这个问题,你可以在这里找到答案:https://dev59.com/YmXWa4cB1Zd3GeqPQ9pr#18805115 - lonecat
2个回答

19

这对我有用。获取“click” href并在拥有“result”的情况下使用它。

  <script>
        $(document).on("click", ".alert", function(e) {
            var link = $(this).attr("href"); // "get" the intended link in a var
            e.preventDefault();    
            bootbox.confirm("Are you sure?", function(result) {    
                if (result) {
                    document.location.href = link;  // if result, "set" the document location       
                }    
            });
        });
    </script>

非常感谢您,这应该是被接受的答案,它救了我的一天。 - user1376704

2

这很棒!

$(".alert").on("click", function (e) {
    // Init
    var self = $(this);
    e.preventDefault();

    // Show Message        
    bootbox.confirm("Are you sure?", function (result) {
        if (result) {                
            self.off("click");
            self.click();
        }
    });
});

谢谢,非常好用。 - Saygın Karahan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接