Custom confirm dialog with JavaScript

前端 未结 3 2019
不知归路
不知归路 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:09

    This really should be done with a callback. The closest thing to what you're after would be to use a publish and subscribe model with some custom events.

    To do so:

    When a user clicks the yes button, trigger a custom event called clickedYes. Do the same for "no"

    $('#yesbtn').click(function(){
        $(document).trigger('clickedYes');
    });
    
    $('#nobtn').click(function(){
        $(document).trigger('clickedNo');
    });
    

    Now we need to "listen" or subscribe for those events and execute the appropriate action in context.

    Lets create a hypothetical situation: Your user clicks delete and you want to confirm that choice.

    First setup what you want to happen if they click yes:

    $(document).unbind('clickedYes'); //Unbind any old actions
    $(document).bind('clickedYes',function(){
        //Code to delete the item
        //Hide the popup
    });
    

    then what you want to happen if they click no:

    $(document).unbind('clickedNo'); //Unbind any old actions
    $(document).bind('clickedNo',function(){
        //Hide the popup and don't delete
    });
    

    So we've setup actions that are listening for clickedYes or clickedNo. Now we just need to show the user the popup so that they have to click yes or no. When they do, they'll trigger the events above.

    so your myConfirm() function will just do the following:

    function myConfirm(msg){
        //change the message to 'msg'
        //Show the popup
    }
    

    So the order would be:

    1. Bind triggers for the custom events to the yes and no buttons
    2. Before prompting - unbind any old actions and attach your new ones
    3. Present the user with a popup that'll cause them to trigger on of your actions.

    This will allow you to call the function like this myConfirm('Are you sure'); It's not quite what you're after...but I don't think it's possible to do exactly what you want.

提交回复
热议问题