Javascript 如何让函数返回onclick函数的结果?

Javascript 如何让函数返回onclick函数的结果?,javascript,jquery,function,Javascript,Jquery,Function,我试图理解如何制作类似于windows.prompt()的东西,如中所示,您调用的是一个函数,它会给出按下按钮的结果。即 var a = customPrompt('message', ['buttonName1','buttonName2']); 我正在寻找一个函数,如: function customPrompt(message, buttonNames){ $('body').append($("<div id='Calert'>").append($("<di

我试图理解如何制作类似于windows.prompt()的东西,如中所示,您调用的是一个函数,它会给出按下按钮的结果。即

var a = customPrompt('message', ['buttonName1','buttonName2']);
我正在寻找一个函数,如:

function customPrompt(message, buttonNames){
    $('body').append($("<div id='Calert'>").append($("<div id='CalertMessage'>").text(message)));
    $('#Calert').append($("<div id='CalertButtons'>"));
    for(var i=0;i<buttonNames.length;i++){
        $('#CalertButtons').append($("<div id='CalertButton'>").text(buttonNames[i]));
    }
    Here, the function needs to return which button was clicked.
}
功能自定义提示(消息、按钮名称){
$('body').append($(“”)。append($(“”)。text(message));
$('#Calert')。追加($(“”);

对于(var i=0;i函数应如下所示:

function customPrompt(message, buttonNames, callback){
    $('body').append($("<div id='Calert'>").append($("<div id='CalertMessage'>").text(message)));
    $('#Calert').append($("<div id='CalertButtons'>"));
    buttonNames.forEach(function(name, index) {
        var $button = $("<div id='CalertButton'>").text(name).appendTo('#CalertButtons'); // create the button
        $button.on('click', function() {                // when the button is clicked
            // probably destroy the dialog box
            callback(name, index);                      // call the callback passing to it the name and the index of the clicked button
        });
    });
}
customPrompt("Hello, wolrd!", ["aaa", "bbb"], function(name, index) {
     // if the user clicks the aaa button then: name === 'aaa' and index === 0
     // if the user clicks the bbb button then: name === 'bbb' and index === 1
});

您不能分配同步事件处理程序。这意味着,当提示符打开时,其他代码不能运行,这通常是您不希望的。@PeterMader我同意,那么windows.prompt()是如何运行的呢执行此操作?从事件处理程序返回,到哪里?@SpencerCornwall
窗口。提示符
。警报
。确认
是具有某些特权的本地人,例如在关闭前停止所有操作。您的DOM提示符没有该特权。您可以使其具有回调,在出现工作时调用结果k完成了。