如何创建一个带有“确定”和“取消”选项的对话框

860
我将制作一个按钮来执行某项操作,并将数据保存到数据库中。
一旦用户点击该按钮,我希望用JavaScript警告框提供“是”和“取消”选项。如果用户选择“是”,则数据将被插入到数据库中,否则不会有任何操作。
如何显示这样的对话框?
17个回答

1603

你可能在寻找confirm(),它可以显示一个提示框,并根据用户的决定返回truefalse

if (confirm('Are you sure you want to save this thing into the database?')) {
  // Save it!
  console.log('Thing was saved to the database.');
} else {
  // Do nothing!
  console.log('Thing was not saved to the database.');
}


164
确认对话框上有“确定”和“取消”按钮。这些按钮可以设置为“是”和“否”吗? - Owen
22
@Owen No. 该规范 表示您只需提供消息即可。您可以在 HTML 中模拟对话框(尽管它不会像内置对话框一样阻止操作)。jQuery 对话框 是实现此类功能的好例子。 - s4y
5
请注意:您可以在 else 语句中加入一个 return,这样您就不需要将所有代码都包裹在 confirm 中!(尽管这是一种逐个修复的解决方案) - Jacob Raccuia
28
或者简单地写成if(!confirm('message')) return; - Aaron
8
在React中使用confirm时,我不得不使用window.confirm来避免出现“意外使用confirm”的错误。 - sebtheiler
显示剩余2条评论

151
var answer = window.confirm("Save data?");
if (answer) {
    //some code
}
else {
    //some code
}

使用 window.confirm 代替 alert。这是实现该功能最简单的方法。


24
你也可以使用if(confirm("...")){},意思与原文相同。 - nicbou

97

如何使用“内联”JavaScript实现此操作:

<form action="http://www.google.com/search">
  <input type="text" name="q" />
  <input type="submit" value="Go"
    onclick="return confirm('Are you sure you want to search Google?')"
  />
</form>

9
最好处理表单的onsubmit事件:使用您的代码,如果用户在文本框中按下回车键,则表单会在没有任何请求的情况下被提交! - p91paul
1
@p91paul - 这个问题出现在哪个浏览器上?我刚刚在Windows上的IE、Chrome和Safari中尝试按下回车键,结果都符合预期。http://jsfiddle.net/ALjge/1/ - dana
1
好的,我当时很确定自己说的话,但是我没有测试就发现我错了。非常抱歉! - p91paul
1
没问题 :) 通常有多种方法可以解决问题。我只是想确认我的方法是否有效。使用你建议的 <form onsubmit="..."> 也可以 :) - dana

48

避免内联 JavaScript - 更改行为意味着需要编辑代码的每个实例,这不太好看!

一个更干净的方式是在元素上使用 data 属性,例如 data-confirm="你的信息"。我的代码支持以下操作,包括动态生成的元素:

  • abutton 点击
  • form 提交
  • option 选择

jQuery:

$(document).on('click', ':not(form)[data-confirm]', function(e){
    if(!confirm($(this).data('confirm'))){
        e.stopImmediatePropagation();
        e.preventDefault();
    }
});

$(document).on('submit', 'form[data-confirm]', function(e){
    if(!confirm($(this).data('confirm'))){
        e.stopImmediatePropagation();
        e.preventDefault();
    }
});

$(document).on('input', 'select', function(e){
    var msg = $(this).children('option:selected').data('confirm');
    if(msg != undefined && !confirm(msg)){
        $(this)[0].selectedIndex = 0;
    }
});

HTML:

<!-- hyperlink example -->
<a href="http://www.example.com" data-confirm="Are you sure you want to load this URL?">Anchor</a>

<!-- button example -->
<button type="button" data-confirm="Are you sure you want to click the button?">Button</button>

<!-- form example -->
<form action="http://www.example.com" data-confirm="Are you sure you want to submit the form?">
    <button type="submit">Submit</button>
</form>

<!-- select option example -->
<select>
    <option>Select an option:</option>
    <option data-confirm="Are you want to select this option?">Here</option>
</select>

JSFiddle演示


2
之前从没想到过如此干净的解决方案。不过,它甚至可以更加简洁:$("[data-confirm]").on('click,submit', function() { /* ... */ }) - Grimace of Despair
1
抱歉,我忍不住再次查看它。首先:事件应该用空格分隔。其次:您仍然可以压缩代码http://jsfiddle.net/jguEg/ ;) - Grimace of Despair
@GrimaceofDespair 我已经更新了代码,因为点击并确认 type="button" 然后询问用户是否要提交表单(因为您正在点击表单元素),显然在再次点击 OK 后没有发生任何事情。 - rybo111
1
这些都是很好的例子,尽管它们都使用 confirm() 对话框,所以你无法重命名取消/确定按钮 :| - rogerdpack
@rogerdpack 是的,但使用数据属性的美妙之处在于您可以更改 confirm() 而不更改 HTML。 - rybo111

39

你需要创建一个自定义的确认框(confirmBox)。无法更改通过confirm函数显示的对话框中的按钮。

jQuery 确认框(confirmBox)


请参考这个例子:https://jsfiddle.net/kevalbhatt18/6uauqLn6/

<div id="confirmBox">
    <div class="message"></div>
    <span class="yes">Yes</span>
    <span class="no">No</span>
</div>
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
});

纯JavaScript确认框


示例: http://jsfiddle.net/kevalbhatt18/qwkzw3rg/127/

<div id="id_confrmdiv">confirmation
    <button id="id_truebtn">Yes</button>
    <button id="id_falsebtn">No</button>
</div>

<button onclick="doSomething()">submit</button>

脚本

<script>
    function doSomething(){
        document.getElementById('id_confrmdiv').style.display="block"; //this is the replace of this line

        document.getElementById('id_truebtn').onclick = function(){
           // Do your delete operation
            alert('true');
        };
        document.getElementById('id_falsebtn').onclick = function(){
             alert('false');
           return false;
        };
    }
</script>

CSS

body { font-family: sans-serif; }

#id_confrmdiv
{
    display: none;
    background-color: #eee;
    border-radius: 5px;
    border: 1px solid #aaa;
    position: fixed;
    width: 300px;
    left: 50%;
    margin-left: -150px;
    padding: 6px 8px 8px;
    box-sizing: border-box;
    text-align: center;
}

#id_confrmdiv button {
    background-color: #ccc;
    display: inline-block;
    border-radius: 3px;
    border: 1px solid #aaa;
    padding: 2px;
    text-align: center;
    width: 80px;
    cursor: pointer;
}

#id_confrmdiv .button:hover
{
    background-color: #ddd;
}

#confirmBox .message
{
    text-align: left;
    margin-bottom: 8px;
}

2
太好了,非常简单,纯JavaScript,CSS也不多。喜欢它:D - m3nda
确认框应该在项目被按下后消失。此外,您应该使用类而不是ID。 - rybo111
如果您喜欢这个答案,那么您可以点赞@rogerdpack :P - Keval Bhatt
@AndriiMuzychuk,是的,你可以这样做。 - Keval Bhatt
2
大家好,你们有非常好的例子,这是一个概念验证。如果你不喜欢它,请根据自己的需要进行调整,不要责怪作者。请注意,jquery confirmBox 的示例链接不再有效。顺便说一下,纯 JS 是很好的示例。 - m3nda
显示剩余6条评论

17

或者简单点说:

<a href="https://some-link.com/" onclick="return confirm('Are you sure you want to go to that link?');">click me!</a>

1
谢谢!我担心我必须在我的简单CRUD应用程序中包含jQuery,只是为了做一个简单的“您确定要删除吗?”。 - Will Matheson

15

这个插件可以帮助你更轻松地使用 jquery-confirm


$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    confirm: function(){
        alert('Confirmed!');
    },
    cancel: function(){
        alert('Canceled!')
    }
});

9
这是一个使用原生JavaScript实现的完全响应式解决方案:

// Call function when show dialog btn is clicked
document.getElementById("btn-show-dialog").onclick = function(){show_dialog()};
var overlayme = document.getElementById("dialog-container");

function show_dialog() {
 /* A function to show the dialog window */
    overlayme.style.display = "block";
}

// If confirm btn is clicked , the function confim() is executed
document.getElementById("confirm").onclick = function(){confirm()};
function confirm() {
 /* code executed if confirm is clicked */   
    overlayme.style.display = "none";
}

// If cancel btn is clicked , the function cancel() is executed
document.getElementById("cancel").onclick = function(){cancel()};
function cancel() {
 /* code executed if cancel is clicked */  
    overlayme.style.display = "none";
}
.popup {
  width: 80%;
  padding: 15px;
  left: 0;
  margin-left: 5%;
  border: 1px solid rgb(1,82,73);
  border-radius: 10px;
  color: rgb(1,82,73);
  background: white;
  position: absolute;
  top: 15%;
  box-shadow: 5px 5px 5px #000;
  z-index: 10001;
  font-weight: 700;
  text-align: center;
}

.overlay {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,.85);
  z-index: 10000;
  display :none;
}

@media (min-width: 768px) {
  .popup {
    width: 66.66666666%;
    margin-left: 16.666666%;
  }
}
@media (min-width: 992px) {
  .popup {
    width: 80%;
    margin-left: 25%;
  }
}
@media (min-width: 1200px) {
  .popup {
    width: 33.33333%;
    margin-left: 33.33333%;
  }
}

.dialog-btn {
  background-color:#44B78B;
  color: white;
  font-weight: 700;
  border: 1px solid #44B78B;
  border-radius: 10px;
  height: 30px;
  width: 30%;
}
.dialog-btn:hover {
  background-color:#015249;
  cursor: pointer;
}
<div id="content_1" class="content_dialog">
    <p>Lorem ipsum dolor sit amet. Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit.</p>
    <p>Aliquam erat volutpat. Maecenas non tortor nulla, non malesuada velit. Nullam felis tellus, tristique nec egestas in, luctus sed diam. Suspendisse potenti.</p>
</div>

<button id="btn-show-dialog">Ok</button>


<div class="overlay" id="dialog-container">
  <div class="popup">
    <p>This will be saved. Continue ?</p>
    <div class="text-right">
      <button class="dialog-btn btn-cancel" id="cancel">Cancel</button>
      <button class="dialog-btn btn-primary" id="confirm">Ok</button>
    </div>
  </div>
</div>


9
你可以使用JavaScript拦截onSubmit事件。

然后调用确认提示,然后获取结果。


6
另一种方法是:
$("input[name='savedata']").click(function(e){
       var r = confirm("Are you sure you want to save now?");

       //cancel clicked : stop button default action 
       if (r === false) {
           return false;
        }

        //action continues, saves in database, no need for more code


   });

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