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

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

如何显示这样的对话框?


当前回答

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

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

其他回答

与其他解决方案不同的另一个解决方案是使用新的对话框元素。您需要使用基于与其他元素交互的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>

我可以使用吗?

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

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>

用Yes和No按钮制作了一个超级简单的小香草js确认对话框。很遗憾我们不能定制本地的。

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

一个普通的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>

自定义模式对话框.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 buttons
        var 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