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

时间:2022-12-15 14:29:25

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对话框替换丑陋的javascript:alert()框。在我的场景中,我有一个条目列表,在每个条目的旁边,我将为每个条目设置一个“delete”按钮。psuedo 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(!)。我如何设置这些确认按钮的行为,以便,如果用户仍然选择YES,它将跟随链接删除它?

23 个解决方案

#1


160  

I just had to solve the same problem. The key to getting this to work was that the dialog must be partially initialized in the click event 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.

我只需要解决同样的问题。实现该功能的关键是,必须在要使用确认功能的链接的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 jsfiddle with 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.

为了充分披露,我将注意到我在这个问题上花了几分钟的时间,我对这个问题给出了类似的答案,当时也没有一个公认的答案。

#2


59  

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的答案并不十分有效,因为他在单击事件上实例化对话框后设置选项的方式不正确。这是我的代码。我没有按照保罗的例子来定制它,但它只是猫的胡须在某些元素的命名上的不同。你应该能算出来。更正位于“单击事件”按钮对话框选项的setter中。

$(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.

希望这能帮助别人,因为这篇文章最初让我走上了正确的道路,我认为我最好把改正贴出来。

#3


27  

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.

继续。

#4


6  

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"添加到你的a链接中,它就会工作!

#5


6  

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事件(单击),如果没有确认对话框就会触发。惟一的区别是不同的事件名称空间(在本例中为“confirm”),因此不会再次显示确认对话框。然后,Jquery本地机制可以接管,并且可以按照预期运行。另一个优点是它可以用于按钮和超链接。我希望我讲得够清楚。

#6


4  

I know this is an old question but here is my solution using HTML5 data attributes in 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");
});

#7


3  

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');
});

#8


3  

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方法来实际执行操作。

#9


2  

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元素,您可以根据需要进行调整。

#10


2  

(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 confirm插件。它的使用非常简单,在很多情况下都是如此。

#11


1  

As much as I hate to use eval, it seemed like the easiest way for me, without causing a lot of problems depending on different circumstances. Similar to the javascript settimeout function.

尽管我很讨厌使用eval,但它对我来说似乎是最简单的方法,而不需要根据不同的情况造成很多问题。类似于javascript settimeout函数。

<a href="#" onclick="javascript:confirm('do_function(params)');">Confirm</a>
<div id="dialog-confirm" title="Confirm" style="display:none;">
    <p>Are you sure you want to do this?</p>
</div>
<script>
function confirm(callback){
    $( "#dialog-confirm" ).dialog({
        resizable: false,
        height:140,
        modal: false,
        buttons: {
            "Ok": function() {
                $( this ).dialog( "close" );
                eval(callback)
            },
            Cancel: function() {
                $( this ).dialog( "close" );
                return false;
            }
        }
    });
}

function do_function(params){
    console.log('approved');
}
</script>

#12


1  

I ran into this myself and ended up with a solution, that is similar to several answers here, but implemented slightly differently. I didn't like many pieces of javascript, or a placeholder div somewhere. I wanted a generalized solution, that could then be used in HTML without adding javascript for each use. Here is what I came up with (this requires jquery ui):

我自己遇到了这个问题,最后得到了一个解决方案,它与这里的几个答案相似,但实现方式略有不同。我不喜欢很多javascript,或者某个地方的占位符div。我想要一个通用的解决方案,然后可以在HTML中使用,而不必每次都添加javascript。这是我想到的(这需要jquery ui):

Javascript:

Javascript:

$(function() {

  $("a.confirm").button().click(function(e) {

    e.preventDefault();

    var target = $(this).attr("href");
    var content = $(this).attr("title");
    var title = $(this).attr("alt");

    $('<div>' + content + '</div>'). dialog({
      draggable: false,
      modal: true,
      resizable: false,
      width: 'auto',
      title: title,
      buttons: {
        "Confirm": function() {
          window.location.href = target;
        },
        "Cancel": function() {
          $(this).dialog("close");
        }
      }
    });

  });

});

And then in HTML, no javascript calls or references are needed:

然后在HTML中,不需要javascript调用或引用:

<a href="http://www.google.com/"
   class="confirm"
   alt="Confirm test"
   title="Are you sure?">Test</a>

Since the title attribute is used for the div content, the user can even get the confirmation question by hovering over the button (which is why i didn't user the title attribute for the tile). The title of the confirmation window is the content of the alt tag. The javascript snip can be included in a generalized .js include, and simply by applying a class you have a pretty confirmation window.

由于title属性用于div内容,因此用户甚至可以通过在按钮上悬停来获得确认问题(这就是为什么我不使用这个块的title属性)。确认窗口的标题是alt标记的内容。javascript snip可以包含在一个一般化的.js中,并且简单地应用一个类,您就有了一个漂亮的确认窗口。

#13


0  

$("ul li a").live('click', function (e) {
            e.preventDefault();

            $('<div></div>').appendTo('body')
                    .html('<div><h6>Are you sure about this?</h6></div>')
                    .dialog({
                        modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
                        width: 'auto', modal: true, resizable: false,
                        buttons: {
                            Confirm: function () {
                                // $(obj).removeAttr('onclick');                                
                                // $(obj).parents('.Parent').remove();

                                $(this).dialog("close");

                                window.location.reload();
                            },
                            No: function () {
                                $(this).dialog("close");
                            }
                        },
                        Cancel: function (event, ui) {
                            $(this).remove();
                        }
                    });

            return false;
        });

#14


0  

NOTE: Not enough rep to comment but BineG's answer works perfectly in resolving postback issues with ASPX pages as highlighted by Homer and echo. In honor, here's a variation using a dynamic dialog.

注意:没有足够的代表进行评论,但是BineG的回答可以很好地解决ASPX页面的回发问题。为了表示敬意,这里有一个使用动态对话框的变体。

$('#submit-button').bind('click', function(ev) {
    var $btn = $(this);
    ev.preventDefault();
    $("<div />").html("Are you sure?").dialog({
        modal: true,
        title: "Confirmation",
        buttons: [{
            text: "Ok",
            click: function() {
                $btn.trigger("click.confirmed");
                $(this).dialog("close");
            }
        }, {
            text: "Cancel",
            click: function() {
                $(this).dialog("close");
            }
        }]
    }).show();  
});

#15


0  

Easy way with a touch of javascript

简单的方法和一点javascript

$("#myButton").click(function(event) {
    var cont = confirm('Continue?');
    if(cont) {
        // do stuff here if OK was clicked
        return true;
    }
    // If cancel was clicked button execution will be halted.
    event.preventDefault();
}

#16


0  

Another variation of the above where it checks if the control is either a 'asp:linkbutton' or 'asp:button' which renders as two different html controls. Seems to work just fine for me but haven't tested it extensively.

上面的另一种变体,它检查控件是“asp:linkbutton”还是“asp:button”,它们呈现为两个不同的html控件。似乎对我来说很好,但还没有对它进行广泛的测试。

        $(document).on("click", ".confirm", function (e) {
            e.preventDefault();
            var btn = $(this);
            $("#dialog").dialog('option', 'buttons', {
                "Confirm": function () {
                    if (btn.is("input")) {                            
                        var name = btn.attr("name");
                        __doPostBack(name, '')
                    }
                    else {
                        var href = btn.attr("href");
                        window.location.href = href;
                    }
                    $(this).dialog("close");
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            });

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

#17


0  

I was looking for this to use on link-buttons within an ASP.NET Gridview (GridView Control build in Commands) So the "Confirm" action in the dialog needs to activate a script generated by the Gridview control at run-time. this worked for me:

我想在ASP中的链接按钮上使用它。NET Gridview(命令中生成的Gridview控件),因此对话框中的“确认”操作需要激活Gridview控件在运行时生成的脚本。这工作对我来说:

 $(".DeleteBtnClass").click(function (e) {
     e.preventDefault();
     var inlineFunction = $(this).attr("href") + ";";
     $("#dialog").dialog({
         buttons: {
             "Yes": function () {
                 eval(inlineFunction); // eval() can be harmful!
             },
                 "No": function () {
                 $(this).dialog("close");
             }
         }
     });
 });

#18


0  

I know this question is old but this was my first time I had to use a confirmation dialog. I think this is the shortest way to do it.

我知道这个问题由来已久,但这是我第一次使用确认对话框。我认为这是最短的方法。

$(element).onClick(function(){ // This can be a function or whatever, this is just a trigger
  var conBox = confirm("Are you sure ?");
    if(conBox){ 
        // Do what you have to do
    }
    else
        return;
});

I hope you like it :)

希望你喜欢

#19


0  

Personally I see this as a recurrent requirement in many views of many ASP.Net MVC applications.

我个人认为在许多ASP视图中,这是一个重复的需求。净MVC应用程序。

That's why I defined a model class and a partial view:

这就是为什么我定义了一个模型类和一个局部视图:

using Resources;

namespace YourNamespace.Models
{
  public class SyConfirmationDialogModel
  {
    public SyConfirmationDialogModel()
    {
      this.DialogId = "dlgconfirm";
      this.DialogTitle = Global.LblTitleConfirm;
      this.UrlAttribute = "href";
      this.ButtonConfirmText = Global.LblButtonConfirm;
      this.ButtonCancelText = Global.LblButtonCancel;
    }

    public string DialogId { get; set; }
    public string DialogTitle { get; set; }
    public string DialogMessage { get; set; }
    public string JQueryClickSelector { get; set; }
    public string UrlAttribute { get; set; }
    public string ButtonConfirmText { get; set; }
    public string ButtonCancelText { get; set; }
  }
}

And my partial view:

和我的部分视图:

@using YourNamespace.Models;

@model SyConfirmationDialogModel

<div id="@Model.DialogId" title="@Model.DialogTitle">
  @Model.DialogMessage
</div>

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

    $("@Model.JQueryClickSelector").click(function (e) {
      e.preventDefault();
      var sTargetUrl = $(this).attr("@Model.UrlAttribute");

      $("#@Model.DialogId").dialog({
        buttons: {
          "@Model.ButtonConfirmText": function () {
            window.location.href = sTargetUrl;
          },  
          "@Model.ButtonCancelText": function () {
            $(this).dialog("close");
          }
        }
      });

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

And then, every time you need it in a view, you just use @Html.Partial (in did it in section scripts so that JQuery is defined):

然后,每次在视图中需要它时,只需使用@Html。部分(在部分脚本中,这样定义JQuery):

@Html.Partial("_ConfirmationDialog", new SyConfirmationDialogModel() { DialogMessage = Global.LblConfirmDelete, JQueryClickSelector ="a[class=SyLinkDelete]"})

The trick is to specify the JQueryClickSelector that will match the elements that need a confirmation dialog. In my case, all anchors with the class SyLinkDelete but it could be an identifier, a different class etc. For me it was a list of:

诀窍是指定将匹配需要确认对话框的元素的JQueryClickSelector。在我的例子中,所有的锚都有类SyLinkDelete,但它可以是一个标识符,一个不同的类等等。

<a title="Delete" class="SyLinkDelete" href="/UserDefinedList/DeleteEntry?Params">
    <img class="SyImageDelete" alt="Delete" src="/Images/DeleteHS.png" border="0">
</a>

#20


0  

Very popular topic and google finds this for "jquery dialog close which event was clicked" query. My solution handles YES,NO,ESC_KEY,X events properly. I want my callback function be called no matter how dialog was disposed.

非常流行的主题,谷歌为“jquery关闭哪个事件被单击”查询找到这个。我的解决方案是正确的,不,ESC_KEY,X事件。无论如何处理对话框,我都希望调用回调函数。

function dialog_YES_NO(sTitle, txt, fn) {
    $("#dialog-main").dialog({
        title: sTitle,
        resizable: true,
        //height:140,
        modal: true,
        open: function() { $(this).data("retval", false); $(this).text(txt); },
        close: function(evt) {
            var arg1 = $(this).data("retval")==true;
            setTimeout(function() { fn(arg1); }, 30);
        },
        buttons: {
            "Yes": function() { $(this).data("retval", true); $(this).dialog("close"); },
            "No": function()  { $(this).data("retval", false); $(this).dialog("close"); }
        }
    });
}
- - - - 
dialog_YES_NO("Confirm Delete", "Delete xyz item?", function(status) {
   alert("Dialog retval is " + status);
});

It's easy to redirect browser to a new url or perform something else on function retval.

将浏览器重定向到新url或在函数retval上执行其他操作很容易。

#21


0  

So many good answers here ;) Here is my approach. Similiar to eval() usage.

这里有很多很好的答案;这是我的方法。类似eval()使用。

function functionExecutor(functionName, args){
    functionName.apply(this, args);
}

function showConfirmationDialog(html, functionYes, fYesArgs){
    $('#dialog').html(html);
    $('#dialog').dialog({
        buttons : [
            {
                text:'YES',
                click: function(){
                    functionExecutor(functionYes, fYesArgs);
                    $(this).dialog("close");
                },
                class:'green'
            },
            {
                text:'CANCEL',
                click: function() {
                    $(this).dialog("close");
                },
                class:'red'
            }
        ]
    });     
}

And the usage looks like:

用法如下:

function myTestYesFunction(arg1, arg2){
    alert("You clicked YES:"+arg1+arg2);
}

function toDoOrNotToDo(){
    showConfirmationDialog("Dialog text", myTestYesFunction, ['My arg 1','My arg 2']);
}

#22


0  

Out of the box JQuery UI offers this solution:

JQuery UI提供了以下解决方案:

$( function() {
    $( "#dialog-confirm" ).dialog({
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $( this ).dialog( "close" );
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
    });
  } );

HTML

HTML

<div id="dialog-confirm" title="Empty the recycle bin?">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;">
 </span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

You can further customize this by providing a name for the JQuery function and passing the text/title you want displayed as a parameter.

您可以通过为JQuery函数提供一个名称并将希望显示的文本/标题作为参数传递来进一步定制它。

Reference: https://jqueryui.com/dialog/#modal-confirmation

参考:https://jqueryui.com/dialog/ # modal-confirmation

#23


-1  

Well this is the answer of your questions...

这就是你问题的答案……

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE>Santa Luisa</TITLE>
<style>
    body{margin:0;padding:0;background-color:#ffffff;}
    a:link {color:black;}    
a:visited {color:black;}  
a:hover {color:red;}  
a:active {color:red;}
</style>

</HEAD>
<body>

<link rel="stylesheet" href="jquery/themes/base/jquery.ui.all.css">
    <script src="jquery-1.4.4.js"></script>

    <script src="external/jquery.bgiframe-2.1.2.js"></script>
    <script src="ui/jquery.ui.core.js"></script>

    <script src="ui/jquery.ui.widget.js"></script>
    <script src="ui/jquery.ui.mouse.js"></script>
    <script src="ui/jquery.ui.draggable.js"></script>
    <script src="ui/jquery.ui.position.js"></script>

    <script src="ui/jquery.ui.resizable.js"></script>
    <script src="ui/jquery.ui.dialog.js"></script>

    <link rel="stylesheet" href="demos.css">
    <script>
    var lastdel;
    $(function() {
        $( "#dialog" ).dialog({
            autoOpen: false,modal: true,closeOnEscape: true
        });

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

        });


        $("#si").click( function() {
            $('#dialog').dialog('close');
            window.location.href =lastdel;

        });
        $("#no").click( function() {
            $('#dialog').dialog('close');
        });
    });

    </script>

<SCRIPT LANGUAGE="JavaScript">
<!--
        var currentimgx;
        var cimgoverx=200-6;
        var cimgoutx=200;


        function overbx(obj){
        color='#FF0000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';


        currentimgx.style.width=cimgoverx+"px";
        currentimgx.style.height=cimgoverx+"px"; 

    }

    function outbx(obj){
        obj.style.borderTopWidth = '0px';   
        obj.style.borderLeftWidth = '0px';
        obj.style.borderRightWidth = '0px';
        obj.style.borderBottomWidth = '0px';

        currentimgx.style.width=cimgoutx+"px";
        currentimgx.style.height=cimgoutx+"px"; 
    }

function ifocusx(obj){
        color='#FF0000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';

    }

    function iblurx(obj){
        color='#000000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';
    }

    function cimgx(obj){
        currentimgx=obj;
    }


    function pause(millis){
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date < millis);
    } 


//-->
</SCRIPT>
<div id="dialog" title="CONFERMA L`AZIONE" style="text-align:center;">
    <p><FONT  COLOR="#000000" style="font-family:Arial;font-size:22px;font-style:bold;COLOR:red;">CONFERMA L`AZIONE:<BR>POSSO CANCELLARE<BR>QUESTA RIGA ?</FONT></p>

    <p><INPUT TYPE="submit" VALUE="SI" NAME="" id="si"> --><INPUT TYPE="submit" VALUE="NO" NAME="" id="no"></p>
</div>



<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%" height="100%">
<TR valign="top" align="center">
    <TD>
    <FONT COLOR="red" style="font-family:Arial;font-size:25px;font-style:bold;color:red;">Modifica/Dettagli:<font style="font-family:Arial;font-size:20px;font-style:bold;background-color:yellow;color:red;">&nbsp;298&nbsp;</font><font style="font-family:Arial;font-size:20px;font-style:bold;background-color:red;color:yellow;">dsadas&nbsp;sadsadas&nbsp;</font>&nbsp;</FONT>
    </TD>
</TR>

<tr valign="top">
    <td align="center">
        <TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">
        <TR align="left">

            <TD>
                <TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">

                <TR align="left">
                    <TD>
                    <font style="font-sixe:30px;"><span style="color:red;">1</span></font><br><TABLE class="tabela" CELLSPACING="0" CELLPADDING="0" BORDER="1" WIDTH="800px"><TR style="color:white;background-color:black;"><TD align="center">DATA</TD><TD align="center">CODICE</TD><TD align="center">NOME/NOMI</TD><TD  align="center">TESTO</TD><td>&nbsp;</td><td>&nbsp;</td></TR><TR align="center"><TD>12/22/2010&nbsp;</TD><TD>298&nbsp;</TD><TD>daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</TD><TD><A HREF="modificarigadiario.php?codice=298"  style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);"  style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=1';alert(lastdel);" class="confirmLink">Cancella</A></TD><TR align="center"><TD>22/10/2010&nbsp;</TD><TD>298&nbsp;</TD><TD>dfdsfsdfsf</TD><TD><A HREF="modificarigadiario.php?codice=298"  style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);"  style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=2';alert(lastdel);" class="confirmLink">Cancella</A></TD></TABLE><font style="font-sixe:30px;"><span style="color:red;">1</span></font><br>

                    </TD>
                </TR>

                </TABLE>
            </TD>
        </TR>
        </TABLE>
    </td>
</tr>
</tbody></table>


</body>
</html>

make sure you have jquery 1.4.4 and jquery.ui

确保您有jquery 1.4.4和jquery.ui

#1


160  

I just had to solve the same problem. The key to getting this to work was that the dialog must be partially initialized in the click event 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.

我只需要解决同样的问题。实现该功能的关键是,必须在要使用确认功能的链接的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 jsfiddle with 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.

为了充分披露,我将注意到我在这个问题上花了几分钟的时间,我对这个问题给出了类似的答案,当时也没有一个公认的答案。

#2


59  

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的答案并不十分有效,因为他在单击事件上实例化对话框后设置选项的方式不正确。这是我的代码。我没有按照保罗的例子来定制它,但它只是猫的胡须在某些元素的命名上的不同。你应该能算出来。更正位于“单击事件”按钮对话框选项的setter中。

$(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.

希望这能帮助别人,因为这篇文章最初让我走上了正确的道路,我认为我最好把改正贴出来。

#3


27  

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.

继续。

#4


6  

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"添加到你的a链接中,它就会工作!

#5


6  

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事件(单击),如果没有确认对话框就会触发。惟一的区别是不同的事件名称空间(在本例中为“confirm”),因此不会再次显示确认对话框。然后,Jquery本地机制可以接管,并且可以按照预期运行。另一个优点是它可以用于按钮和超链接。我希望我讲得够清楚。

#6


4  

I know this is an old question but here is my solution using HTML5 data attributes in 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");
});

#7


3  

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');
});

#8


3  

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方法来实际执行操作。

#9


2  

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元素,您可以根据需要进行调整。

#10


2  

(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 confirm插件。它的使用非常简单,在很多情况下都是如此。

#11


1  

As much as I hate to use eval, it seemed like the easiest way for me, without causing a lot of problems depending on different circumstances. Similar to the javascript settimeout function.

尽管我很讨厌使用eval,但它对我来说似乎是最简单的方法,而不需要根据不同的情况造成很多问题。类似于javascript settimeout函数。

<a href="#" onclick="javascript:confirm('do_function(params)');">Confirm</a>
<div id="dialog-confirm" title="Confirm" style="display:none;">
    <p>Are you sure you want to do this?</p>
</div>
<script>
function confirm(callback){
    $( "#dialog-confirm" ).dialog({
        resizable: false,
        height:140,
        modal: false,
        buttons: {
            "Ok": function() {
                $( this ).dialog( "close" );
                eval(callback)
            },
            Cancel: function() {
                $( this ).dialog( "close" );
                return false;
            }
        }
    });
}

function do_function(params){
    console.log('approved');
}
</script>

#12


1  

I ran into this myself and ended up with a solution, that is similar to several answers here, but implemented slightly differently. I didn't like many pieces of javascript, or a placeholder div somewhere. I wanted a generalized solution, that could then be used in HTML without adding javascript for each use. Here is what I came up with (this requires jquery ui):

我自己遇到了这个问题,最后得到了一个解决方案,它与这里的几个答案相似,但实现方式略有不同。我不喜欢很多javascript,或者某个地方的占位符div。我想要一个通用的解决方案,然后可以在HTML中使用,而不必每次都添加javascript。这是我想到的(这需要jquery ui):

Javascript:

Javascript:

$(function() {

  $("a.confirm").button().click(function(e) {

    e.preventDefault();

    var target = $(this).attr("href");
    var content = $(this).attr("title");
    var title = $(this).attr("alt");

    $('<div>' + content + '</div>'). dialog({
      draggable: false,
      modal: true,
      resizable: false,
      width: 'auto',
      title: title,
      buttons: {
        "Confirm": function() {
          window.location.href = target;
        },
        "Cancel": function() {
          $(this).dialog("close");
        }
      }
    });

  });

});

And then in HTML, no javascript calls or references are needed:

然后在HTML中,不需要javascript调用或引用:

<a href="http://www.google.com/"
   class="confirm"
   alt="Confirm test"
   title="Are you sure?">Test</a>

Since the title attribute is used for the div content, the user can even get the confirmation question by hovering over the button (which is why i didn't user the title attribute for the tile). The title of the confirmation window is the content of the alt tag. The javascript snip can be included in a generalized .js include, and simply by applying a class you have a pretty confirmation window.

由于title属性用于div内容,因此用户甚至可以通过在按钮上悬停来获得确认问题(这就是为什么我不使用这个块的title属性)。确认窗口的标题是alt标记的内容。javascript snip可以包含在一个一般化的.js中,并且简单地应用一个类,您就有了一个漂亮的确认窗口。

#13


0  

$("ul li a").live('click', function (e) {
            e.preventDefault();

            $('<div></div>').appendTo('body')
                    .html('<div><h6>Are you sure about this?</h6></div>')
                    .dialog({
                        modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
                        width: 'auto', modal: true, resizable: false,
                        buttons: {
                            Confirm: function () {
                                // $(obj).removeAttr('onclick');                                
                                // $(obj).parents('.Parent').remove();

                                $(this).dialog("close");

                                window.location.reload();
                            },
                            No: function () {
                                $(this).dialog("close");
                            }
                        },
                        Cancel: function (event, ui) {
                            $(this).remove();
                        }
                    });

            return false;
        });

#14


0  

NOTE: Not enough rep to comment but BineG's answer works perfectly in resolving postback issues with ASPX pages as highlighted by Homer and echo. In honor, here's a variation using a dynamic dialog.

注意:没有足够的代表进行评论,但是BineG的回答可以很好地解决ASPX页面的回发问题。为了表示敬意,这里有一个使用动态对话框的变体。

$('#submit-button').bind('click', function(ev) {
    var $btn = $(this);
    ev.preventDefault();
    $("<div />").html("Are you sure?").dialog({
        modal: true,
        title: "Confirmation",
        buttons: [{
            text: "Ok",
            click: function() {
                $btn.trigger("click.confirmed");
                $(this).dialog("close");
            }
        }, {
            text: "Cancel",
            click: function() {
                $(this).dialog("close");
            }
        }]
    }).show();  
});

#15


0  

Easy way with a touch of javascript

简单的方法和一点javascript

$("#myButton").click(function(event) {
    var cont = confirm('Continue?');
    if(cont) {
        // do stuff here if OK was clicked
        return true;
    }
    // If cancel was clicked button execution will be halted.
    event.preventDefault();
}

#16


0  

Another variation of the above where it checks if the control is either a 'asp:linkbutton' or 'asp:button' which renders as two different html controls. Seems to work just fine for me but haven't tested it extensively.

上面的另一种变体,它检查控件是“asp:linkbutton”还是“asp:button”,它们呈现为两个不同的html控件。似乎对我来说很好,但还没有对它进行广泛的测试。

        $(document).on("click", ".confirm", function (e) {
            e.preventDefault();
            var btn = $(this);
            $("#dialog").dialog('option', 'buttons', {
                "Confirm": function () {
                    if (btn.is("input")) {                            
                        var name = btn.attr("name");
                        __doPostBack(name, '')
                    }
                    else {
                        var href = btn.attr("href");
                        window.location.href = href;
                    }
                    $(this).dialog("close");
                },
                "Cancel": function () {
                    $(this).dialog("close");
                }
            });

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

#17


0  

I was looking for this to use on link-buttons within an ASP.NET Gridview (GridView Control build in Commands) So the "Confirm" action in the dialog needs to activate a script generated by the Gridview control at run-time. this worked for me:

我想在ASP中的链接按钮上使用它。NET Gridview(命令中生成的Gridview控件),因此对话框中的“确认”操作需要激活Gridview控件在运行时生成的脚本。这工作对我来说:

 $(".DeleteBtnClass").click(function (e) {
     e.preventDefault();
     var inlineFunction = $(this).attr("href") + ";";
     $("#dialog").dialog({
         buttons: {
             "Yes": function () {
                 eval(inlineFunction); // eval() can be harmful!
             },
                 "No": function () {
                 $(this).dialog("close");
             }
         }
     });
 });

#18


0  

I know this question is old but this was my first time I had to use a confirmation dialog. I think this is the shortest way to do it.

我知道这个问题由来已久,但这是我第一次使用确认对话框。我认为这是最短的方法。

$(element).onClick(function(){ // This can be a function or whatever, this is just a trigger
  var conBox = confirm("Are you sure ?");
    if(conBox){ 
        // Do what you have to do
    }
    else
        return;
});

I hope you like it :)

希望你喜欢

#19


0  

Personally I see this as a recurrent requirement in many views of many ASP.Net MVC applications.

我个人认为在许多ASP视图中,这是一个重复的需求。净MVC应用程序。

That's why I defined a model class and a partial view:

这就是为什么我定义了一个模型类和一个局部视图:

using Resources;

namespace YourNamespace.Models
{
  public class SyConfirmationDialogModel
  {
    public SyConfirmationDialogModel()
    {
      this.DialogId = "dlgconfirm";
      this.DialogTitle = Global.LblTitleConfirm;
      this.UrlAttribute = "href";
      this.ButtonConfirmText = Global.LblButtonConfirm;
      this.ButtonCancelText = Global.LblButtonCancel;
    }

    public string DialogId { get; set; }
    public string DialogTitle { get; set; }
    public string DialogMessage { get; set; }
    public string JQueryClickSelector { get; set; }
    public string UrlAttribute { get; set; }
    public string ButtonConfirmText { get; set; }
    public string ButtonCancelText { get; set; }
  }
}

And my partial view:

和我的部分视图:

@using YourNamespace.Models;

@model SyConfirmationDialogModel

<div id="@Model.DialogId" title="@Model.DialogTitle">
  @Model.DialogMessage
</div>

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

    $("@Model.JQueryClickSelector").click(function (e) {
      e.preventDefault();
      var sTargetUrl = $(this).attr("@Model.UrlAttribute");

      $("#@Model.DialogId").dialog({
        buttons: {
          "@Model.ButtonConfirmText": function () {
            window.location.href = sTargetUrl;
          },  
          "@Model.ButtonCancelText": function () {
            $(this).dialog("close");
          }
        }
      });

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

And then, every time you need it in a view, you just use @Html.Partial (in did it in section scripts so that JQuery is defined):

然后,每次在视图中需要它时,只需使用@Html。部分(在部分脚本中,这样定义JQuery):

@Html.Partial("_ConfirmationDialog", new SyConfirmationDialogModel() { DialogMessage = Global.LblConfirmDelete, JQueryClickSelector ="a[class=SyLinkDelete]"})

The trick is to specify the JQueryClickSelector that will match the elements that need a confirmation dialog. In my case, all anchors with the class SyLinkDelete but it could be an identifier, a different class etc. For me it was a list of:

诀窍是指定将匹配需要确认对话框的元素的JQueryClickSelector。在我的例子中,所有的锚都有类SyLinkDelete,但它可以是一个标识符,一个不同的类等等。

<a title="Delete" class="SyLinkDelete" href="/UserDefinedList/DeleteEntry?Params">
    <img class="SyImageDelete" alt="Delete" src="/Images/DeleteHS.png" border="0">
</a>

#20


0  

Very popular topic and google finds this for "jquery dialog close which event was clicked" query. My solution handles YES,NO,ESC_KEY,X events properly. I want my callback function be called no matter how dialog was disposed.

非常流行的主题,谷歌为“jquery关闭哪个事件被单击”查询找到这个。我的解决方案是正确的,不,ESC_KEY,X事件。无论如何处理对话框,我都希望调用回调函数。

function dialog_YES_NO(sTitle, txt, fn) {
    $("#dialog-main").dialog({
        title: sTitle,
        resizable: true,
        //height:140,
        modal: true,
        open: function() { $(this).data("retval", false); $(this).text(txt); },
        close: function(evt) {
            var arg1 = $(this).data("retval")==true;
            setTimeout(function() { fn(arg1); }, 30);
        },
        buttons: {
            "Yes": function() { $(this).data("retval", true); $(this).dialog("close"); },
            "No": function()  { $(this).data("retval", false); $(this).dialog("close"); }
        }
    });
}
- - - - 
dialog_YES_NO("Confirm Delete", "Delete xyz item?", function(status) {
   alert("Dialog retval is " + status);
});

It's easy to redirect browser to a new url or perform something else on function retval.

将浏览器重定向到新url或在函数retval上执行其他操作很容易。

#21


0  

So many good answers here ;) Here is my approach. Similiar to eval() usage.

这里有很多很好的答案;这是我的方法。类似eval()使用。

function functionExecutor(functionName, args){
    functionName.apply(this, args);
}

function showConfirmationDialog(html, functionYes, fYesArgs){
    $('#dialog').html(html);
    $('#dialog').dialog({
        buttons : [
            {
                text:'YES',
                click: function(){
                    functionExecutor(functionYes, fYesArgs);
                    $(this).dialog("close");
                },
                class:'green'
            },
            {
                text:'CANCEL',
                click: function() {
                    $(this).dialog("close");
                },
                class:'red'
            }
        ]
    });     
}

And the usage looks like:

用法如下:

function myTestYesFunction(arg1, arg2){
    alert("You clicked YES:"+arg1+arg2);
}

function toDoOrNotToDo(){
    showConfirmationDialog("Dialog text", myTestYesFunction, ['My arg 1','My arg 2']);
}

#22


0  

Out of the box JQuery UI offers this solution:

JQuery UI提供了以下解决方案:

$( function() {
    $( "#dialog-confirm" ).dialog({
      resizable: false,
      height: "auto",
      width: 400,
      modal: true,
      buttons: {
        "Delete all items": function() {
          $( this ).dialog( "close" );
        },
        Cancel: function() {
          $( this ).dialog( "close" );
        }
      }
    });
  } );

HTML

HTML

<div id="dialog-confirm" title="Empty the recycle bin?">
  <p><span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;">
 </span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>

You can further customize this by providing a name for the JQuery function and passing the text/title you want displayed as a parameter.

您可以通过为JQuery函数提供一个名称并将希望显示的文本/标题作为参数传递来进一步定制它。

Reference: https://jqueryui.com/dialog/#modal-confirmation

参考:https://jqueryui.com/dialog/ # modal-confirmation

#23


-1  

Well this is the answer of your questions...

这就是你问题的答案……

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML>
<HEAD>
<TITLE>Santa Luisa</TITLE>
<style>
    body{margin:0;padding:0;background-color:#ffffff;}
    a:link {color:black;}    
a:visited {color:black;}  
a:hover {color:red;}  
a:active {color:red;}
</style>

</HEAD>
<body>

<link rel="stylesheet" href="jquery/themes/base/jquery.ui.all.css">
    <script src="jquery-1.4.4.js"></script>

    <script src="external/jquery.bgiframe-2.1.2.js"></script>
    <script src="ui/jquery.ui.core.js"></script>

    <script src="ui/jquery.ui.widget.js"></script>
    <script src="ui/jquery.ui.mouse.js"></script>
    <script src="ui/jquery.ui.draggable.js"></script>
    <script src="ui/jquery.ui.position.js"></script>

    <script src="ui/jquery.ui.resizable.js"></script>
    <script src="ui/jquery.ui.dialog.js"></script>

    <link rel="stylesheet" href="demos.css">
    <script>
    var lastdel;
    $(function() {
        $( "#dialog" ).dialog({
            autoOpen: false,modal: true,closeOnEscape: true
        });

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

        });


        $("#si").click( function() {
            $('#dialog').dialog('close');
            window.location.href =lastdel;

        });
        $("#no").click( function() {
            $('#dialog').dialog('close');
        });
    });

    </script>

<SCRIPT LANGUAGE="JavaScript">
<!--
        var currentimgx;
        var cimgoverx=200-6;
        var cimgoutx=200;


        function overbx(obj){
        color='#FF0000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';


        currentimgx.style.width=cimgoverx+"px";
        currentimgx.style.height=cimgoverx+"px"; 

    }

    function outbx(obj){
        obj.style.borderTopWidth = '0px';   
        obj.style.borderLeftWidth = '0px';
        obj.style.borderRightWidth = '0px';
        obj.style.borderBottomWidth = '0px';

        currentimgx.style.width=cimgoutx+"px";
        currentimgx.style.height=cimgoutx+"px"; 
    }

function ifocusx(obj){
        color='#FF0000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';

    }

    function iblurx(obj){
        color='#000000';
        width='3px';
        obj.style.borderTopWidth = width;
        obj.style.borderTopColor =color;
        obj.style.borderTopStyle ='solid';

        obj.style.borderLeftWidth = width;
        obj.style.borderLeftColor =color;
        obj.style.borderLeftStyle ='solid';

        obj.style.borderRightWidth = width;
        obj.style.borderRightColor =color;
        obj.style.borderRightStyle ='solid';

        obj.style.borderBottomWidth = width;
        obj.style.borderBottomColor =color;
        obj.style.borderBottomStyle ='solid';
    }

    function cimgx(obj){
        currentimgx=obj;
    }


    function pause(millis){
    var date = new Date();
    var curDate = null;

    do { curDate = new Date(); }
    while(curDate-date < millis);
    } 


//-->
</SCRIPT>
<div id="dialog" title="CONFERMA L`AZIONE" style="text-align:center;">
    <p><FONT  COLOR="#000000" style="font-family:Arial;font-size:22px;font-style:bold;COLOR:red;">CONFERMA L`AZIONE:<BR>POSSO CANCELLARE<BR>QUESTA RIGA ?</FONT></p>

    <p><INPUT TYPE="submit" VALUE="SI" NAME="" id="si"> --><INPUT TYPE="submit" VALUE="NO" NAME="" id="no"></p>
</div>



<TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="100%" height="100%">
<TR valign="top" align="center">
    <TD>
    <FONT COLOR="red" style="font-family:Arial;font-size:25px;font-style:bold;color:red;">Modifica/Dettagli:<font style="font-family:Arial;font-size:20px;font-style:bold;background-color:yellow;color:red;">&nbsp;298&nbsp;</font><font style="font-family:Arial;font-size:20px;font-style:bold;background-color:red;color:yellow;">dsadas&nbsp;sadsadas&nbsp;</font>&nbsp;</FONT>
    </TD>
</TR>

<tr valign="top">
    <td align="center">
        <TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">
        <TR align="left">

            <TD>
                <TABLE CELLSPACING="0" CELLPADDING="0" BORDER="0" WIDTH="">

                <TR align="left">
                    <TD>
                    <font style="font-sixe:30px;"><span style="color:red;">1</span></font><br><TABLE class="tabela" CELLSPACING="0" CELLPADDING="0" BORDER="1" WIDTH="800px"><TR style="color:white;background-color:black;"><TD align="center">DATA</TD><TD align="center">CODICE</TD><TD align="center">NOME/NOMI</TD><TD  align="center">TESTO</TD><td>&nbsp;</td><td>&nbsp;</td></TR><TR align="center"><TD>12/22/2010&nbsp;</TD><TD>298&nbsp;</TD><TD>daaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</TD><TD><A HREF="modificarigadiario.php?codice=298"  style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);"  style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=1';alert(lastdel);" class="confirmLink">Cancella</A></TD><TR align="center"><TD>22/10/2010&nbsp;</TD><TD>298&nbsp;</TD><TD>dfdsfsdfsf</TD><TD><A HREF="modificarigadiario.php?codice=298"  style="font-weight:bold;color:red;font-size:30px;">Modifica</A></TD><TD><A HREF="JavaScript:void(0);"  style="font-weight:bold;color:red;font-size:30px;" onclick="$('#dialog').dialog('open');$('#dialog').animate({ backgroundColor: '#aa0000', color: '#fff', width: 250 }, 2000);lastdel='cancellarighe.php?codice=298&id=2';alert(lastdel);" class="confirmLink">Cancella</A></TD></TABLE><font style="font-sixe:30px;"><span style="color:red;">1</span></font><br>

                    </TD>
                </TR>

                </TABLE>
            </TD>
        </TR>
        </TABLE>
    </td>
</tr>
</tbody></table>


</body>
</html>

make sure you have jquery 1.4.4 and jquery.ui

确保您有jquery 1.4.4和jquery.ui