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