如何使用“确定”和“取消”选项创建对话框

我将创建一个按钮来执行操作并将数据保存到数据库中。

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

如何显示这样的对话框?

1290155 次浏览

您可以使用JavaScript拦截onSubmit事件。

然后调用确认警报,然后获取结果。

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

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

您可能正在寻找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.');}

如何使用“内联”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>

避免内联JavaScript-更改行为意味着编辑代码的每个实例,这并不漂亮!

一种更清晰的方法是在元素上使用data属性,例如data-confirm="Your message here"。我下面的代码支持以下操作,包括动态生成的元素:

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

超文本标记语言:

<!-- 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演示

您必须创建一个自定义确认框。无法更改确认功能显示的对话框中的按钮。

jQuery确认框


看这个例子: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 operationalert('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;}

这个插件可以帮助你jQuery确认页易于使用

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

另一种方法来做到这一点:

$("input[name='savedata']").click(function(e){var r = confirm("Are you sure you want to save now?");
//cancel clicked : stop button default actionif (r === false) {return false;}
//action continues, saves in database, no need for more code

});
document.getElementById("button").addEventListener("click", function(e) {var cevap = window.confirm("Satın almak istediğinizden emin misiniz?");if (cevap) {location.href='Http://www.evdenevenakliyat.net.tr';}});

或者简单地说:

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

这是一个使用vanilla javascript的完整响应式解决方案:

// Call function when show dialog btn is clickeddocument.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 executeddocument.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 executeddocument.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>

xdialog提供了一个简单的APIxdialog.confirm()。代码片段如下。可以找到更多演示这里

document.getElementById('test').addEventListener('click', test);
function test() {xdialog.confirm('Are you sure?', function() {// do work here if ok/yes selected...console.info('Done!');}, {style: 'width:420px;font-size:0.8rem;',buttons: {ok: 'yes text',cancel: 'no text'},oncancel: function() {console.warn('Cancelled!');}});}
<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">test</button>

超级简单,微小的香草js确认对话框与是和否按钮。
可惜我们不能自定义原生。

https://www.npmjs.com/package/yesno-dialog

输入图片描述

在点击操作之前询问的最简单方法是以下操作

<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>

我目前正在开发一个已经有自己的通知/对话框的Web工作流,我最近(就像今天一样)创建了一个小型的自定义(并根据项目需求量身定制)YES/NO对话框。

所有对话框都出现在模态层上。需要用户充分注意。

我以这种方式定义选项配置。此选项用于定义按钮文本,以及单击时与每个按钮关联的值:

optionsConfig = [{ text: 'Yes', value: true },{ text: 'No', value: false }]

该函数的使用如下所示:

const answer = await notifier.showDialog('choose an option', options.config);if (answer) {// 'Yes' was clicked} else {// 'No' was clicked!}

我所做的,只是为每个选项创建一个async事件处理程序,这意味着,每个按钮都分配了一个简单的处理程序。每个处理程序返回选项的值。处理程序被推送到数组中。然后将数组传递给Promise.race,这是showDialog方法的返回值,它将对应于value的实际值(处理程序返回的值)。

不能提供太多代码。正如我所说,这是一个非常具体的案例,但这个想法可能对其他实现有用。二十行左右的代码。

另一种解决方案是使用新的dialog元素。您需要使用基于与其他元素交互的showshowModal方法。close方法可用于关闭打开的对话框。

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

const dialogEl = document.querySelector("dialog");const openDialog = document.querySelector("button.open-dialog");const yesBtn = document.querySelector(".yes");const noBtn = document.querySelector(".no");const result = document.querySelector(".result");
openDialog.addEventListener("click", () => {dialogEl.showModal();});
yesBtn.addEventListener("click", () => {// Below line can be replaced by your DB queryresult.textContent = "This could have been your DB query";dialogEl.close();});
noBtn.addEventListener("click", () => {result.textContent = "";dialogEl.close();});
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap');
body {font-family: "Roboto";}
button {background: hsl(206deg 64% 51%);color: white;padding: 0.5em 1em;border: 0 none;cursor: pointer;}
dialog {border: 0 none;}
.result {margin-top: 1em;}
<dialog><button class="yes">Yes</button><button class="no">No</button></dialog><button class="open-dialog">Click me</button><div class="result"></div>

我可以使用吗?

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

一个普通的JavaScript选项,带有一个用于创建自定义模式对话框的类,其中包括一个输入框:

jsfiddle:

https://jsfiddle.net/craigdude/uh82mjtb/2/

html:

<!DOCTYPE html><html>

<style>.modal_dialog{box-sizing: border-box;background-color: #ededed;border-radius: 5px;border: 0.5px solid #ccc;font-family: sans-serif;left: 30%;margin-left: -50px;padding: 15px 10px 10px 5px;position: fixed;text-align: center;width: 320px;}
</style>
<script src="./CustomModalDialog.js"></script>
<script>var gCustomModalDialog = null;

/** this could be static html from the page in an "invisible" state */function generateDynamicCustomDialogHtml(){    
var html = "";html += '<div id="custom_modal_dialog" class="modal_dialog">';html += 'Name: <input id="name" placeholder="Name"></input><br><br>';html += '<button id="okay_button">OK</button>';html += '<button id="cancel_button">Cancel</button>';html += '</div>';return html;}
function onModalDialogOkayPressed(event) {    
var name = document.getElementById("name");alert("Name entered: "+name.value);}
function onModalDialogCancelPressed(event) {    
gCustomModalDialog.hide();}
function setupCustomModalDialog() {
var html = generateDynamicCustomDialogHtml();gCustomModalDialog = new CustomModalDialog(html, "okay_button", "cancel_button","modal_position", onModalDialogOkayPressed, onModalDialogCancelPressed);}

function showCustomModalDialog() {    
if (! gCustomModalDialog) {setupCustomModalDialog();}gCustomModalDialog.show();gCustomModalDialog.setFocus("name");}

</script>
<body>
<button onclick="showCustomModalDialog(this)">Show Dialog</button><br>Some content<div id="modal_position"></div>Some additional content
</body>
</html>

CustomModalDialog.js:

/** Encapsulates a custom modal dialog in pure JS*/class CustomModalDialog {    
/*** Constructs the modal content* @param htmlContent - content of the HTML dialog to show* @param okayControlElementId - elementId of the okay button, image or control* @param cancelControlElementId - elementId of the cancel button, image or control* @param insertionElementId - elementId of the <div> or whatever tag to*            insert the html at within the document* @param callbackOnOkay - method to invoke when the okay button or control is clicked.* @param callbackOnCancel - method to invoke when the cancel button or control is clicked.* @param callbackTag (optional) - to allow object to be passed to the callbackOnOkay*              or callbackOnCancel methods when they're invoked.*/constructor(htmlContent, okayControlElementId, cancelControlElementId, insertionElementId,callbackOnOkay, callbackOnCancel, callbackTag) {
this.htmlContent = htmlContent;this.okayControlElementId = okayControlElementId;this.cancelControlElementId = cancelControlElementId;this.insertionElementId = insertionElementId;this.callbackOnOkay = callbackOnOkay;this.callbackOnCancel = callbackOnCancel;this.callbackTag = callbackTag;}

/** shows the custom modal dialog */show() {// must insert the HTML into the page before searching for ok/cancel buttonsvar insertPoint = document.getElementById(this.insertionElementId);insertPoint.innerHTML = this.htmlContent;        
var okayControl = document.getElementById(this.okayControlElementId);var cancelControl = document.getElementById(this.cancelControlElementId);
okayControl.addEventListener('click', event => {this.callbackOnOkay(event, insertPoint, this.callbackTag);});cancelControl.addEventListener('click', event => {this.callbackOnCancel(event, insertPoint, this.callbackTag);});} // end: method    
    
/** hide the custom modal dialog */hide() {var insertPoint = document.getElementById(this.insertionElementId);var okayControl = document.getElementById(this.okayControlElementId);var cancelControl = document.getElementById(this.cancelControlElementId);
insertPoint.innerHTML = "";        
okayControl.removeEventListener('click',this.callbackOnOkay,false);cancelControl.removeEventListener('click',this.callbackOnCancel,false);} // end: method    
    
/** sets the focus to given element id*/setFocus(elementId) {    
var focusElement = document.getElementById(elementId);focusElement.focus();if (typeof  focusElementstr === "HTMLInputElement")focusElement.select();}
    
} // end: class