我要做一个按钮,采取行动并将数据保存到数据库中。

一旦用户单击按钮,我希望JavaScript警报提供“是”和“取消”选项。如果用户选择“是”,数据将被插入数据库,否则将不采取任何操作。

如何显示这样的对话框?


当前回答

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

使用window.conf而不是alert。这是实现该功能的最简单方法。

其他回答

xdialog提供了一个简单的API xdialog.conf()。代码片段如下。更多演示可在此处找到

document.getElementById('test').addEventListener('click',test);函数测试(){xdialog.conf('确定吗?',function(){//如果选择“确定”/“是”,请在此处工作。。。console.info('Done!');}, {style:'宽度:420px;字体大小:0.8rem;',按钮:{ok:'是文本',cancel:'无文本'},oncancel:function(){console.warn('已取消!');}});}<link href=“https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.css“rel=”stylesheet“/><script src=“https://cdn.jsdelivr.net/gh/xxjapp/xdialog@3/xdialog.min.js“></script><button id=“test”>测试</button>

点击前询问的最简单方法如下

<a onclick="return askyesno('Delete this record?');" href="example.php?act=del&del_cs_id=<?php echo $oid; ?>">
<button class="btn btn-md btn-danger">Delete </button>
</a>

与其他解决方案不同的另一个解决方案是使用新的对话框元素。您需要使用基于与其他元素交互的show或showModal方法。close方法可用于关闭打开的对话框。

<dialog>
  <button class="yes">Yes</button>
  <button class="no">No</button>
</dialog>

const dialogEl=document.querySelector(“对话框”);const openDialog=document.querySelector(“button.open dialog”);const yesBtn=document.querySelector(“.yes”);const noBtn=document.querySelector(“.no”);const result=document.querySelector(“.result”);openDialog.addEventListener(“单击”,()=>{dialogEl.showModal();});yesBtn.addEventListener(“单击”,()=>{//以下行可以由您的DB查询替换result.textContent=“这可能是您的DB查询”;dialogEl.close();});noBtn.addEventListener(“单击”,()=>{result.textContent=“”;dialogEl.close();});@导入url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');正文{字体系列:“Roboto”;}按钮{背景:hsl(206deg 64%51%);颜色:白色;衬垫:0.5em 1em;边框:0无;光标:指针;}对话框{边框:0无;}.结果{页边距:1em;}<对话框><button class=“yes”>是</button><button class=“no”>否</button></dialog><button class=“open dialog”>单击我</button><div class=“result”></div>

我可以使用吗?

目前,与所有现代浏览器的兼容性都很好。

这个插件可以帮助您jquery确认易于使用

$.confirm({
    title: 'Confirm!',
    content: 'Simple confirm!',
    confirm: function(){
        alert('Confirmed!');
    },
    cancel: function(){
        alert('Canceled!')
    }
});
var answer = window.confirm("Save data?");
if (answer) {
    //some code
}
else {
    //some code
}

使用window.conf而不是alert。这是实现该功能的最简单方法。