如何在 Jquery UI 对话框中实现“确认”对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/887029/
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 10:01:48  来源:igfitidea点击:

How to implement "confirmation" dialog in Jquery UI dialog?

jqueryjquery-uidialogmodal-dialog

提问by xandy

I am try to use JQuery UI Dialog to replace the ugly javascript:alert()box. In my scenario, I have a list of items, and next to each individual of them, I would have a "delete" button for each of them. the psuedo html setup will be something follows:

我尝试使用 JQuery UI Dialog 来替换丑陋的javascript:alert()框。在我的场景中,我有一个项目列表,在每个项目旁边,我会为每个项目设置一个“删除”按钮。伪 html 设置如下:

<ul>
    <li>ITEM <a href="url/to/remove"> <span>$itemId</span>
    <li>ITEM <a href="url/to/remove"><span>$itemId</span>
    <li>ITEM <a href="url/to/remove"><span>$itemId</span>
</ul>

<div id="confirmDialog">Are you sure?</div>

In JQ part, on document ready, I would first setup the div to be a modal dialog with necessary button, and set those "a" to be firing to confirmation before to remove, like:

在 JQ 部分,在文档准备好后,我首先将 div 设置为带有必要按钮的模式对话框,并将那些“a”设置为在删除之前触发确认,例如:

$("ul li a").click(function() {
  // Show the dialog    
  return false; // to prevent the browser actually following the links!
}

OK, here's the problem. during the init time, the dialog will have no idea who (item) will fire it up, and also the item id (!). How can I setup the behavior of those confirmation buttons in order to, if the user still choose YES, it will follow the link to remove it?

好的,问题来了。在初始化期间,对话框不知道谁(项目)将启动它,也不知道项目 ID(!)。如何设置这些确认按钮的行为,以便如果用户仍然选择是,它将按照链接将其删除?

回答by Paul Morie

I just had to solve the same problem. The key to getting this to work was that the dialogmust be partially initialized in the clickevent handler for the link you want to use the confirmation functionality with (if you want to use this for more than one link). This is because the target URL for the link must be injected into the event handler for the confirmation button click. I used a CSS class to indicate which links should have the confirmation behavior.

我只需要解决同样的问题。让它工作的关键是dialog必须在click事件处理程序中为要使用确认功能的链接部分初始化(如果您想将其用于多个链接)。这是因为必须将链接的目标 URL 注入到确认按钮单击的事件处理程序中。我使用了一个 CSS 类来指示哪些链接应该具有确认行为。

Here's my solution, abstracted away to be suitable for an example.

这是我的解决方案,抽象出来以适合示例。

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>

<script type="text/javascript">
  $(document).ready(function() {
    $("#dialog").dialog({
      autoOpen: false,
      modal: true
    });
  });

  $(".confirmLink").click(function(e) {
    e.preventDefault();
    var targetUrl = $(this).attr("href");

    $("#dialog").dialog({
      buttons : {
        "Confirm" : function() {
          window.location.href = targetUrl;
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

    $("#dialog").dialog("open");
  });
</script>

<a class="confirmLink" href="http://someLinkWhichRequiresConfirmation.com">Click here</a>
<a class="confirmLink" href="http://anotherSensitiveLink">Or, you could click here</a>

I believe that this would work for you, if you can generate your links with the CSS class (confirmLink, in my example).

如果您可以使用 CSS 类(confirmLink在我的示例中为 )生成链接,我相信这对您有用。

Here is a jsfiddlewith the code in it.

这是一个带有代码的jsfiddle

In the interest of full disclosure, I'll note that I spent a few minutes on this particular problem and I provided a similar answer to this question, which was also without an accepted answer at the time.

在充分披露的利益,我会注意到,我花在这方面的问题了几分钟,我提供了一个类似的答案,这个问题,这也是没有当时是一个公认的答案。

回答by lloydphillips

I found the answer by Paul didn't quite work as the way he was setting the options AFTER the dialog was instantiated on the click event were incorrect. Here is my code which was working. I've not tailored it to match Paul's example but it's only a cat's whisker's difference in terms of some elements are named differently. You should be able to work it out. The correction is in the setter of the dialog option for the buttons on the click event.

我发现 Paul 的答案不太有效,因为他在单击事件上实例化对话框后设置选项的方式不正确。这是我正在运行的代码。我没有定制它来匹配保罗的例子,但它只是猫须的不同,因为某些元素的命名不同。你应该能够解决它。更正位于单击事件按钮的对话框选项的设置器中。

$(document).ready(function() {

    $("#dialog").dialog({
        modal: true,
        bgiframe: true,
        width: 500,
        height: 200,
        autoOpen: false
    });


    $(".lb").click(function(e) {

        e.preventDefault();
        var theHREF = $(this).attr("href");

        $("#dialog").dialog('option', 'buttons', {
            "Confirm" : function() {
                window.location.href = theHREF;
            },
            "Cancel" : function() {
                $(this).dialog("close");
            }
        });

        $("#dialog").dialog("open");

    });

});

Hope this helps someone else as this post originally got me down the right track I thought I'd better post the correction.

希望这对其他人有所帮助,因为这篇文章最初让我走上了正轨,我认为我最好发布更正。

回答by d-coder

I've created a my own function for a jquery ui confirm dialog. Here is the code

我为 jquery ui 确认对话框创建了一个我自己的函数。这是代码

function myConfirm(dialogText, okFunc, cancelFunc, dialogTitle) {
  $('<div style="padding: 10px; max-width: 500px; word-wrap: break-word;">' + dialogText + '</div>').dialog({
    draggable: false,
    modal: true,
    resizable: false,
    width: 'auto',
    title: dialogTitle || 'Confirm',
    minHeight: 75,
    buttons: {
      OK: function () {
        if (typeof (okFunc) == 'function') {
          setTimeout(okFunc, 50);
        }
        $(this).dialog('destroy');
      },
      Cancel: function () {
        if (typeof (cancelFunc) == 'function') {
          setTimeout(cancelFunc, 50);
        }
        $(this).dialog('destroy');
      }
    }
  });
}

Now to use this in your code, simply write following

现在要在您的代码中使用它,只需编写以下内容

myConfirm('Do you want to delete this record ?', function () {
    alert('You clicked OK');
  }, function () {
    alert('You clicked Cancel');
  },
  'Confirm Delete'
);

Go on.

继续。

回答by BineG

This is my solution.. i hope it helps anyone. It's written on the fly instead of copypasted so forgive me for any mistakes.

这是我的解决方案..我希望它可以帮助任何人。它是即时编写的,而不是复制粘贴的,所以请原谅我的任何错误。

$("#btn").on("click", function(ev){
    ev.preventDefault();

    dialog.dialog("open");

    dialog.find(".btnConfirm").on("click", function(){
        // trigger click under different namespace so 
        // click handler will not be triggered but native
        // functionality is preserved
        $("#btn").trigger("click.confirmed");
    }
    dialog.find(".btnCancel").on("click", function(){
        dialog.dialog("close");
    }
});

Personally I prefer this solution :)

我个人更喜欢这个解决方案:)

edit: Sorry.. i really shouldve explained it more in detail. I like it because in my opinion its an elegant solution. When user clicks the button which needs to be confirmed first the event is canceled as it has to be. When the confirmation button is clicked the solution is not to simulate a link click but to trigger the same native jquery event (click) upon the original button which would have triggered if there was no confirmation dialog. The only difference being a different event namespace (in this case 'confirmed') so that the confirmation dialog is not shown again. Jquery native mechanism can then take over and things can run as expected. Another advantage being it can be used for buttons and hyperlinks. I hope i was clear enough.

编辑:对不起..我真的应该更详细地解释一下。我喜欢它,因为在我看来它是一个优雅的解决方案。当用户单击需要首先确认的按钮时,事件将被取消。单击确认按钮时,解决方案不是模拟链接单击,而是在没有确认对话框时触发的原始​​按钮上触发相同的原生 jquery 事件(单击)。唯一的区别是不同的事件命名空间(在本例中为“已确认”),因此不会再次显示确认对话框。然后 Jquery 本机机制可以接管,事情可以按预期运行。另一个优点是它可以用于按钮和超链接。我希望我足够清楚。

回答by user681365

Simple and short solution that i just tried and it works

我刚刚尝试过的简单而简短的解决方案,它有效

  $('.confirm').click(function() {
    $(this).removeClass('confirm');
    $(this).text("Sure?");
    $(this).unbind();
    return false;
  });

then just add the class="confirm" to your a link and it works!

然后只需将 class="confirm" 添加到您的链接中,它就可以工作了!

回答by woggles

I know this is an old question but here is my solution using HTML5 data attributesin MVC4:

我知道这是一个老问题,但这是我在 MVC4 中使用 HTML5数据属性的解决方案:

<div id="dialog" title="Confirmation Required" data-url="@Url.Action("UndoAllPendingChanges", "Home")">
  Are you sure about this?
</div>

JS code:

JS代码:

$("#dialog").dialog({
    modal: true,              
    autoOpen: false,
    buttons: {
        "Confirm": function () {
            window.location.href = $(this).data('url');
        },
        "Cancel": function () {
            $(this).dialog("close");
        }
    }
});

$("#TheIdOfMyButton").click(function (e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

回答by andi

Will this do?

这会吗?

$("ul li a").click(function(e) {
  e.preventDefault();
  $('#confirmDialog').show();

  var delete_path = $(this).attr('href');

  $('#confirmDialog a.ok').unbind('click'); //  just in case the cancel link 
                                            //  is not the  only way you can
                                            //  close your dialog
  $('#confirmDialog a.ok').click(function(e) {
     e.preventDefault();
     window.location.href = delete_path;
  });

});

$('#confirmDialog a.cancel').click(function(e) {
   e.preventDefault();
   $('#confirmDialog').hide();
   $('#confirmDialog a.ok').unbind('click');
});

回答by LukeP

As above. Previous posts got me on the right track. This is how I've done it. The idea is to have an image next to every row in the table (generated by PHP script from database). When an image is clicked, the user would get redirected to the URL, and as a result, the appropriate record would be deleted from the database while showing some data related to the clicked record within jQuery UI Dialog.

如上。以前的帖子让我走上了正轨。我就是这样做的。这个想法是在表中的每一行旁边都有一个图像(由数据库中的 PHP 脚本生成)。单击图像时,用户将被重定向到 URL,因此,相应的记录将从数据库中删除,同时在 jQuery UI 对话框中显示与单击记录相关的一些数据。

The JavaScript code:

JavaScript 代码:

$(document).ready(function () {
  $("#confirmDelete").dialog({
    modal: true,
    bgiframe: true,
    autoOpen: false
  });
});

function confirmDelete(username, id) {
  var delUrl = "/users/delete/" + id;
  $('#confirmDelete').html("Are you sure you want to delete user: '" + username + "'");
  $('#confirmDelete').dialog('option', 'buttons', {
    "No": function () {
      $(this).dialog("close");
    },
    "Yes": function () {
      window.location.href = delUrl;
    }
  });
  $('#confirmDelete').dialog('open');
}

Dialog div:

对话框div:

<div id="confirmDelete" title="Delete User?"></div> 

Image link:

图片链接:

<img src="img/delete.png" alt="Delete User" onclick="confirmDelete('<?=$username;?>','<?=$id;?>');"/>

This way you can pass over the PHP loop values into the dialog box. The only downside is using GET method to actually perform the action.

通过这种方式,您可以将 PHP 循环值传递到对话框中。唯一的缺点是使用 GET 方法来实际执行操作。

回答by grahamesd

(As of 03/22/2016, the download on the page linked to doesn't work. I'm leaving the link here in case the developer fixes it at some point because it's a great little plugin. The original post follows. An alternative, and a link that actually works: jquery.confirm.)

(截至 2016 年 3 月 22 日,链接到的页面上的下载不起作用。我将链接留在这里以防开发人员在某个时候修复它,因为它是一个很棒的小插件。原始帖子如下。一个替代方法,以及一个实际有效的链接:jquery.confirm。)

It may be too simple for your needs, but you could try this jQuery confirm plugin. It's really simple to use and does the job in many cases.

它可能对您的需求来说太简单了,但您可以试试这个jQuery 确认插件。它使用起来非常简单,并且在许多情况下都可以完成工作。

回答by kgiannakakis

How about this:

这个怎么样:

$("ul li a").click(function() {

el = $(this);
$("#confirmDialog").dialog({ autoOpen: false, resizable:false,
                             draggable:true,
                             modal: true,
                             buttons: { "Ok": function() {
                                el.parent().remove();
                                $(this).dialog("close"); } }
                           });
$("#confirmDialog").dialog("open");

return false;
});

I have tested it at this html:

我已经在这个 html 上测试过它:

<ul>
<li><a href="#">Hi 1</a></li>
<li><a href="#">Hi 2</a></li>
<li><a href="#">Hi 3</a></li>
<li><a href="#">Hi 4</a></li>
</ul>

It removes the whole li element, you can adapt it at your needs.

它删除了整个 li 元素,您可以根据需要对其进行调整。