2017-07-04 26 views
2

私はwindows.prompt()のようにする方法を理解しようとしていますが、あなたは関数として呼び出して、ボタンを押した結果を返します。 IE。どうすればonclick関数の結果を返す関数を得ることができますか?

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関数から。ボタンを押すまでウェブページ全体を待つことはできません。

+0

あなたは、同期イベントハンドラを割り当てることはできません。これは、プロンプトが開いている間に他のコードを実行できないことを意味します。 – PeterMader

+0

@PeterMader私は同意します。だから、windows.prompt()はどうしますか? –

+0

イベントハンドラからの戻り値はどこにありますか? – Teemu

答えて

1

機能は次のようにする必要があります:

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 
}); 
関連する問題