jquery ui对话框需要返回值,当用户按下按钮,但不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6049687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:18:29  来源:igfitidea点击:

jquery ui dialog box need to return value, when user presses button, but not working

jqueryjquery-ui

提问by Ronedog

I'v got a jquery ui dialog box I want to use to prompt the user to confirm a deletion. When the user presses "yes" or "no" I need to return "True" or "False" to continue some javascript execution. The problem with the code below is when the dialog box shows up it immediately is executing a "return true;" but the user hasn't pressed the "Yes" button yet?

我有一个 jquery ui 对话框,我想用它来提示用户确认删除。当用户按“是”或“否”时,我需要返回“真”或“假”以继续执行一些 javascript。下面代码的问题是当对话框出现时它立即执行“return true;” 但用户还没有按下“是”按钮?

What am I doing wrong?

我究竟做错了什么?

HTML:

HTML:

<div id="modal_confirm_yes_no" title="Confirm"></div>

Javascript call:

Javascript调用:

$("#modal_confirm_yes_no").html("Are you sure you want to delete this?");
var answer = $("#modal_confirm_yes_no").dialog("open");

if (answer)
{
     //delete
}
else
{
     //don't delete
}

Jquery dialog:

Jquery对话框:

$("#modal_confirm_yes_no").dialog({
                bgiframe: true,
                autoOpen: false,
                minHeight: 200,
                width: 350,
                modal: true,
                closeOnEscape: false,
                draggable: false,
                resizable: false,
                buttons: {
                        'Yes': function(){
                            $(this).dialog('close');
                            return true;
                        },
                        'No': function(){
                            $(this).dialog('close');
                            return false;
                        }
                    }
            });

回答by Naftali aka Neal

javascript is asynchronous.

javascript 是异步的。

so you have to use callbacks:

所以你必须使用回调:

   $("#modal_confirm_yes_no").dialog({
            bgiframe: true,
            autoOpen: false,
            minHeight: 200,
            width: 350,
            modal: true,
            closeOnEscape: false,
            draggable: false,
            resizable: false,
            buttons: {
                    'Yes': function(){
                        $(this).dialog('close');
                        callback(true);
                    },
                    'No': function(){
                        $(this).dialog('close');
                        callback(false);
                    }
                }
        });
    function callback(value){
         //do something
    }

回答by BobRodes

If anyone needs a graphic demonstration of asynchronous behavior, here's one that might be helpful. Wrap Ronedog's dialog in a function. I've used "showConfirm" below. Capture the return value in a variable. Call it in some button click event, and try to alert what button was pressed:

如果有人需要异步行为的图形演示,这里有一个可能会有所帮助。将 Ronedog 的对话框包装在一个函数中。我在下面使用了“showConfirm”。捕获变量中的返回值。在某个按钮点击事件中调用它,并尝试提醒按下了什么按钮:

$('.btn').on('click', function(event) {
    var cVal = showConfirm('Really?');
    alert('User pressed ' + cVal);  
});

You will find that you always get the alert before you have a chance to press the button. Since javascript is asynchronous, the alert function doesn't have to wait for the result of the showConfirm function.

你会发现你总是在有机会按下按钮之前收到警报。由于 javascript 是异步的,alert 函数不必等待 showConfirm 函数的结果。

If you then set up the function Neal's way everything will work (thanks Neal).

如果您随后以 Neal 的方式设置函数,一切都会正常工作(感谢 Neal)。

回答by Jze

U should see this answer.

你应该看到这个答案。

Well, This can work.

嗯,这可以工作。

Your dialog function... showDialog()

你的对话功能... showDialog()

function confirmation(question) {
    var defer = $.Deferred();
    $('<div></div>')
        .html(question)
        .dialog({
            autoOpen: true,
            modal: true,
            title: 'Confirmation',
            buttons: {
                "Yes": function () {
                     $(this).dialog("close");
                    defer.resolve("true");//this text 'true' can be anything. But for this usage, it should be true or false.

                },
                "No": function () {
                    $(this).dialog("close");
                    defer.resolve("false");//this text 'false' can be anything. But for this usage, it should be true or false.

                }
            },
            close: function () {
                $(this).remove();
            }
        });
    return defer.promise();
}

and then the code where you use the function...

然后是您使用该功能的代码...

function onclick(){
    var question = "Do you want to start a war?";
    confirmation(question).then(function (answer) {

        if(answer=="true"){
            alert("this is obviously " + ansbool);//TRUE
        } else {
            alert("and then there is " + ansbool);//FALSE
        }
    });
}

This may seem wrong for most people. But there is always some situations where you just can't go without return from JQuery Dialog.

这对大多数人来说似乎是错误的。但总有一些情况,你不能不从 JQuery Dialog 返回。

This will basically mimic the confirm() function. But with ugly code and a nice confirm box look :)

这将基本上模仿 confirm() 函数。但是带有丑陋的代码和漂亮的确认框外观:)

I hope this helps some people out.

我希望这可以帮助一些人。

Honestly,I was take many time for this, finally i found best solution.you can see more detail here=>Awesome Solution

老实说,我为此花了很多时间,最后我找到了最佳解决方案。您可以在此处查看更多详细信息=>很棒的解决方案

回答by Rahul Varadkar

You need to use callback functions. Here is the working example:

您需要使用回调函数。这是工作示例:

Following is the fa-icon. When user clicks it it calls javascript.

以下是 fa 图标。当用户单击它时,它会调用 javascript。

  <a href="#" id="removeNode"><i class="fa fa-minus-circle fa-lg"></i></a>

Following is the javascript code executed when user click "Remove Node" fa icon.

以下是用户单击“删除节点”fa 图标时执行的 javascript 代码。

$("a#removeNode").click(function(){
  // returns the attribute of "selected" Table Row either it is expanded or collapsed based on it's class 
  var datattid = $("tr.expanded.selected, tr.collapsed.selected").attr("data-tt-id"); 
  //alert($("tr.expanded.selected").attr("data-tt-id"));  
  if(typeof datattid != 'undefined'){
    //alert(datattid);
    displayConfirmDialog("You are trying to remove selected node : " + datattid + ". Are you sure?", proceedToRemoveNode);
  }else 
  {
    showErrorDialog("Invalid Row Selection", "Node is not selected.\n You must select the node to remove it." );
  //  displayMessage ("#dialog-message", "Invalid Row Selection", "ui-icon-heart",  "Node is not selected.\n You must select the node to remove it." );  
  }
});

The displayConfirmDialog displays the confirmation message and based on use action it calls the callback function. Here is the code of displayConfirmDialog.

displayConfirmDialog 显示确认消息,并根据使用动作调用回调函数。下面是 displayConfirmDialog 的代码。

//Confirmation dialog to remove node
function displayConfirmDialog(message, proceedWithRequest)
{
    var retVal;

    $("div#dialog-confirm").find("p").html(message);

    var confirmDlg = $( "#dialog-confirm" ).dialog({
          resizable: false,
          height: "auto",
          width: 400,
          modal: true,
          buttons: {
          "Remove Node": function() {
            this.retVal = true;
            proceedWithRequest()  
            $( this ).dialog( "close" );
          },
          Cancel: function() {
            this.retVal = false;
            $( this ).dialog( "close" );
          }
        },
        show:{effect:'scale', duration: 700},
        hide:{effect:'explode', duration: 700}  
    });

    confirmDlg.dialog("open");  
}

Following is the callback function:

以下是回调函数:

//Callback function called if user  confirms to remove node.
function proceedToRemoveNode()
{
  var datattid = $("tr.expanded.selected, tr.collapsed.selected").attr("data-tt-id"); 
  $("#nh_table").treetable("removeNode", datattid);
  showErrorDialog("Node removed successfully", "The node " + datattid + " is removed successfully" );
//  alert("The node " + datattid + " is removed successfully");
}

Following is images of working application that deletes node from a TreeTable using JQuery.

以下是使用 JQuery 从 TreeTable 中删除节点的工作应用程序的图像。

enter image description here

在此处输入图片说明

After confirmation the node "qa-2" is removed from the Tree as shown in following image.

确认后,节点“qa-2”将从树中删除,如下图所示。

enter image description here

在此处输入图片说明

回答by harsha

function confirm() {
        $("#dialog-message").dialog({
                modal : true,
                buttons: {
                    "Yes" : function() {
                        $(this).dialog("close");
                        document.forms[0].action = "actionname-yes";

                        document.forms[0].submit();                         
                    },
                    "No" : function() {
                            $(this).dialog("close");
                            document.forms[0].action = "actionname-no";
                            document.forms[0].submit();
                    }       
                }
        });