javascript - 如何获得返回 onclick 函数结果的函数?

标签 javascript jquery function

我正在尝试了解如何制作类似 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.
}

我遇到的主要问题是,如果我给按钮一个 onclick,那么它就违反了范围,而且我无法从我的 customPrompt 函数返回。但我不能完全让我的整个网页等到按下按钮。

最佳答案

函数应该是这样的:

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

关于javascript - 如何获得返回 onclick 函数结果的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44912327/

相关文章:

C中按下按键后连续调用函数

javascript - 从 dom-repeat 中的元素触发 CustomEvent

javascript - 需要通过javascript和php从检查的项目中提取数据库信息

javascript - 将 Javascript 代码注入(inject)网页

javascript - 如何在调整大小时更改字体大小以适合其父框?

php - 如何以最低复杂度且只有一次返回来处理错误

c - 在 C 函数的参数中声明变量

javascript - 在另一个函数中传递单击元素的属性

javascript - Vue 删除动态组件列表中错误的 HTML 节点

javascript - 无法跨域获取格式错误的 JSON