使用jQuery创建一个“是”或“否”确认框,是吗?

143

我想使用jQuery生成是/否弹窗,而不是确定/取消按钮:

jQuery.alerts.okButton = 'Yes';
jQuery.alerts.cancelButton = 'No';                  
jConfirm('Are you sure??',  '', function(r) {
    if (r == true) {                    
        //Ok button pressed...
    }  
}

还有其他的选择吗?


2
Dupe,https://dev59.com/n3A75IYBdhLWcg3wrbG_ - David Yell
这个发布的代码有效吗?我应该用什么替换'jQuery'?它对我不起作用...我猜我应该使用$,但是怎么做?语法是什么? - sqlchild
3
$.alerts.okButton = '是'; $.alerts.cancelButton = '否'; jConfirm('确定吗?', '', function(r) { if (r == true) { // 按下了"是"按钮... } }); - Sushanth CS
2
另一个 JQuery Dialog 解决方案更像是返回 confirm() 函数的结果:https://dev59.com/72Yr5IYBdhLWcg3wVYzJ#18474005 希望这能帮到你。 - Pierre
https://dev59.com/03A75IYBdhLWcg3wAUF9#10753619 - Thulasiram
显示剩余2条评论
9个回答

146
抱歉,我无法按照您的要求完成任务。我只能回答您的问题和提供相关信息。
ConfirmDialog('Are you sure');

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

          $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');

          $(this).dialog("close");
        },
        No: function() {
          $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');

          $(this).dialog("close");
        }
      },
      close: function(event, ui) {
        $(this).remove();
      }
    });
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>


2
这是jQuery-UI还是普通的jQuery?我在jQuery的文档中没有看到.dialog()。 - chovy
12
你需要在你的页面中包含jQuery和jQuery UI脚本。 - Thulasiram
@Thulasiram,我该如何在yii2框架中添加插件? - Moeez

143

警告方法会阻塞执行,直到用户关闭它:

使用 confirm 函数:

if (confirm('Some message')) {
    alert('Thanks for confirming');
} else {
    alert('Why did you press cancel? You should have confirmed');
}

11
"确认"的意思是“确定”或“取消”,而不是“是”或“否”。 - KlaymenDK

74
我曾使用这些代码:
HTML:
<a id="delete-button">Delete</a>

jQuery:

<script>
$("#delete-button").click(function(){
    if(confirm("Are you sure you want to delete this?")){
        $("#delete-button").attr("href", "query.php?ACTION=delete&ID='1'");
    }
    else{
        return false;
    }
});
</script>

这些代码对我来说可行,但我不确定这是否合适。你认为呢?


3
更短的代码:return confirm("确定要退回该电表吗?") - Павел Зорин

28

13

我看到的所有示例都不能用于不同的“是/否”类型问题的可重复使用。我正在寻找一些允许我指定回调的东西,以便我可以在任何情况下调用它。

以下对我非常有效:

$.extend({ confirm: function (title, message, yesText, yesCallback) {
    $("<div></div>").dialog( {
        buttons: [{
            text: yesText,
            click: function() {
                yesCallback();
                $( this ).remove();
            }
        },
        {
            text: "Cancel",
            click: function() {
                $( this ).remove();
            }
        }
        ],
        close: function (event, ui) { $(this).remove(); },
        resizable: false,
        title: title,
        modal: true
    }).text(message).parent().addClass("alert");
}
});

我接着这样调用它:

var deleteOk = function() {
    uploadFile.del(fileid, function() {alert("Deleted")})
};

$.confirm(
    "CONFIRM", //title
    "Delete " + filename + "?", //message
    "Delete", //button text
    deleteOk //"yes" callback
);

6
我在获取对话框的答案时遇到了麻烦,但最终通过结合此其他问题中的答案(显示“是”和“否”按钮而非“确定”和“取消”)和模态确认对话框代码的一部分找到了解决方案。
以下是其他问题中建议的方法:
创建自己的确认框:
<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>

创建自己的confirm()方法:
function doConfirm(msg, yesFn, noFn)
{
    var confirmBox = $("#confirmBox");
    confirmBox.find(".message").text(msg);
    confirmBox.find(".yes,.no").unbind().click(function()
    {
        confirmBox.hide();
    });
    confirmBox.find(".yes").click(yesFn);
    confirmBox.find(".no").click(noFn);
    confirmBox.show();
}

用您的代码来调用它:

doConfirm("Are you sure?", function yes()
{
    form.submit();
}, function no()
{
    // do nothing
});

我的更改 我对上述代码进行了调整,不再调用confirmBox.show()而是使用confirmBox.dialog({...}),如下所示:

confirmBox.dialog
    ({
      autoOpen: true,
      modal: true,
      buttons:
        {
          'Yes': function () {
            $(this).dialog('close');
            $(this).find(".yes").click();
          },
          'No': function () {
            $(this).dialog('close');
            $(this).find(".no").click();
          }
        }
    });

我所做的另一个改变是在doConfirm函数内创建confirmBox div,就像ThulasiRam在他的回答中所做的那样。

0

我需要对“确定”和“取消”按钮进行翻译。我修改了代码以接受动态文本(调用我的翻译函数)。


$.extend({
    confirm: function(message, title, okAction) {
        $("<div></div>").dialog({
            // Remove the closing 'X' from the dialog
            open: function(event, ui) { $(".ui-dialog-titlebar-close").hide(); },
            width: 500,
            buttons: [{
                text: localizationInstance.translate("Ok"),
                click: function () {
                    $(this).dialog("close");
                    okAction();
                }
            },
                {
                text: localizationInstance.translate("Cancel"),
                click: function() {
                    $(this).dialog("close");
                }
            }],
            close: function(event, ui) { $(this).remove(); },
            resizable: false,
            title: title,
            modal: true
        }).text(message);
    }
});


0

试试这个...非常简单,只需使用带有YES|NO的确认对话框进行警告。

如果(confirm("您想要升级吗?")){ 您的代码 }


-3
你可以重用你的确认框:
    function doConfirm(body, $_nombrefuncion)
    {   var param = undefined;
        var $confirm = $("<div id='confirm' class='hide'></div>").dialog({
            autoOpen: false,
            buttons: {
                Yes: function() {
                param = true;
                $_nombrefuncion(param);
                $(this).dialog('close');
            },
                No: function() {
                param = false;
                $_nombrefuncion(param);
                $(this).dialog('close');
            }
                                    }
        });
        $confirm.html("<h3>"+body+"<h3>");
        $confirm.dialog('open');                                     
    };

// for this form just u must change or create a new function for to reuse the confirm
    function resultadoconfirmresetVTyBFD(param){
        $fecha = $("#asigfecha").val();
        if(param ==true){
              // DO THE CONFIRM
        }
    }

//Now just u must call the function doConfirm
    doConfirm('body message',resultadoconfirmresetVTyBFD);

2
请使用正确的英语,避免缩写,如“u”。此外,最好能够解释一下您的代码以说明和教育OP,并说明为什么您认为您的答案比之前发布的任何答案都更好。 - Davidmh

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