单击“确认”对话框按钮时,如何返回true或false

How may I return true or false when I click on confirm dialog button?

本文关键字:返回 true false 何返回 确认 对话框 按钮 单击      更新时间:2023-09-26

我有一段jQuery

$(function () {
    $('.checked').click(function (e) {
        e.preventDefault();
        var dirtyvalue = "Test1";
        var textvalue= "Test";
        if (dirtyvalue.toLowerCase() != textvalue.toLowerCase()) {
            {
                var dialog = $('<p>Do you want to save your changes?</p>').dialog({
                    buttons: {
                        "Yes": function () {
                            dialog.dialog('close');
                            alert('yes btn called');
                        },
                        "No": function () {
                            dialog.dialog('close');
                            alert('No btn called');
                        },
                        "Cancel": function () {
                            dialog.dialog('close');
                        }
                    }
                });
            }
            return false;
        }
        return true;
    });
});

我想在点击按钮时返回true或false;'"Yes"应返回true,"No"应返回true,"Cancel"应返回false。

我已经检查了这个链接,但这并不能解决我的问题。另请参阅我之前的问题。

我的场景是,我有许多ActionLink和TreeView链接,它们导航到各自的页面。假设我在第1页上有这个JS,并且在该页上有许多操作链接。点击第2页,此时我的确认应该打开,当我点击"否"按钮时,它应该重定向到第2页。

对话框不能返回值,必须将要执行的操作放入另一个函数中。例如

        var dialog = $('<p>Are you sure?</p>').dialog({
            buttons: {
                "Yes": function() 
                       {
                         alert('you chose yes');
                         //call a function that redirects you
                         function_redirect(true);
                       },
                "No":  function() 
                       {
                         alert('you chose no');
                          //call a function that redirects you
                         function_redirect(true);
                       },
                "Cancel":  function() 
                           {
                            alert('you chose cancel');
                         //just close the dialog
                            dialog.dialog('close');
                           }
            }
        });
var function_redirect = function(redirect){
   if(redirect === true){
       //redirect to page2
    }
}

你应该把你需要实现的逻辑放在"function_redirect"(或你想要的任何函数)中,并根据按下的按钮传递参数

编辑-如果你需要知道点击了什么按钮,只需使用传递给函数的事件对象

 "Yes": function(e) {
      //e.target is the element of the dom that has been clicked 
      //from e.target you can understand where you are and act accordingly
      //or pass it to function_redirect
      function_redirect(true, e.target);
var function_redirect = function(redirect, target){
   if(redirect === true){
       if($(target).parent().attr('id') === 'page2'){
          //redirect to page2
       }else{
         //do something else
        }
    }
}

对话框异步工作。所以你不能返回任何值。您应该使用回调函数。

$("a").click(dialog.dialog("open"),function(data){
     //do your redirect here
})