Custom confirm dialog with JavaScript

前端 未结 3 2039
不知归路
不知归路 2021-01-02 09:57

I would like to create a JavaScript function similar to confirm() that shows a dialog (a div with a question and 2 buttons) and returns true if the

3条回答
  •  天命终不由人
    2021-01-02 10:16

    Rather than waiting for the user's input and then returning from the function, it is more common in JavaScript to provide a callback function that will be called when the action you're waiting for is complete. For example:

    myCustomConfirm("Are you sure?", function (confirmed) {
        if (confirmed) {
            // Whatever you need to do if they clicked confirm
        } else {
            // Whatever you need to do if they clicked cancel
        }
    });
    

    This could be implemented along the lines of:

    function myCustomConfirm(message, callback) {
        var confirmButton, cancelButton;
    
        // Create user interface, display message, etc.
    
        confirmButton.onclick = function() { callback(true); };
        cancelButton.onclick = function() { callback(false); };
    }
    

提交回复
热议问题