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

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

如何显示这样的对话框?


当前回答

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

我可以使用吗?

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

其他回答

如何使用“inline”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的完全响应解决方案:

//单击显示对话框btn时调用函数document.getElementById(“btn show dialog”).onclick=function(){show_dialog()};var overlayme=document.getElementById(“对话框容器”);函数show_dialog(){/*显示对话框窗口的函数*/overlayme.style.display=“块”;}//如果单击确认btn,则执行函数confim()document.getElementById(“confirm”).onclick=function(){confirm()};函数确认(){/*单击确认时执行的代码*/overlayme.style.display=“无”;}//如果单击cancel btn,则执行函数cancel()document.getElementById(“cancel”).onclick=function(){cancel()};函数cancel(){/*单击取消时执行的代码*/overlayme.style.display=“无”;}.popup{宽度:80%;填充:15px;左:0;剩余利润:5%;边框:1px实心rgb(1.82,73);边界半径:10px;颜色:rgb(1.82,73);背景:白色;位置:绝对;顶部:15%;盒子阴影:5px 5px 5px#000;z指数:10001;字号:700;文本对齐:居中;}.覆盖{位置:固定;宽度:100%;顶部:0;左:0;右:0;底部:0;背景:rgba(0,0,0,.85);z指数:10000;显示:无;}@介质(最小宽度:768px){.popup{宽度:66.66666666%;剩余利润:16.4666666%;}}@介质(最小宽度:992px){.popup{宽度:80%;剩余利润:25%;}}@媒体(最小宽度:1200px){.popup{宽度:33.33333%;剩余利润:33.33333%;}}对话框btn{背景色:#44B78B;颜色:白色;字号:700;边框:1px实心#44B78B;边界半径:10px;高度:30px;宽度:30%;}对话框btn:悬停{背景色:#015249;光标:指针;}<div id=“content_1”class=“content_dialog”><p>Lorem ipsum dolor坐amet。阿利夸姆拉特(Aliquam erat volutpat)。无侵权行为,无恶意行为</p><p>阿利夸姆拉特(Aliquam erat volutpat)。无侵权行为,无恶意行为。Nullam felis tellus,tristique nec egestas in,luctus sed diam.Suspendiss potenti</p></div><button id=“btn show dialog”>确定</button><div class=“overlay”id=“dialog container”><div class=“popup”><p>这将被保存。是否继续</p><div class=“text right”><button class=“dialog btn btn cancel”id=“cancel”>取消</button><button class=“dialog btn btn primary”id=“confirm”>确定</button></div></div></div>

我目前正在开发一个web工作流,它已经有了自己的通知/对话框,我最近(比如今天)创建了一个小型的自定义(并根据项目需要定制)是/否对话框。

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

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

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

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

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

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

更干净的方法是在元素上使用数据属性,例如dataconfirm=“Your message here”。下面的代码支持以下操作,包括动态生成的元素:

a并单击按钮表单提交选项选择

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

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