ページがロードされるとすぐにイベントハンドラを設定するには、triggerButton
の定義を "api関数"の外側に配置する必要があります。あなたの問題の解決方法は次のとおりです。
$(document).ready(function(){
var webData = null;
$.getJSON('http://example.com', function(data){
//inside this function I call another api using the data response.
$.get('example.url', function(response){
//do something with this data of the response and ended function
});
// expose the data to be used by button click event hander or other
// funcitons that care about the data
webData = data;
});
// Set the event handler
$('#button').on('click', triggerButton);
// define the handler
function triggerButton() {
if(webData){
// do something with the webData
}else{
// display some information that tells the user the status
alert('loading...');
}
}
});
別のアプローチは、API応答がそれぞれ受信された後、前にクリックイベントを処理するために2つのイベントハンドラを使用して です。 APIの応答を受け取る前にボタンのクリックを気にしない場合は、最初のイベントハンドラを省略できます。あなたがAPI要求がボタンのクリック後に送信されたい場合は、(それがより明確にするために、ここで別の関数を使用)イベントハンドラ内でそれらを移動することができ、他に
$(document).ready(function(){
// Set the event handler before resource is loaded
$('#button').on('click', triggerButton);
// define the handler
function triggerButton() {
// display some information that tells the user the status
alert('loading...');
}
$.getJSON('http://example.com', function(data){
//inside this function I call another api using the data response.
$.get('example.url', function(response){
//do something with this data of the response and ended function
});
// update the event handler
$('#button').off('click', triggerButton).on('click', function(){
// do some things...
});
});
});
:ここでは一例である
$(document).ready(function(){
var webData = null;
var loading = false;
function loadData(){
$.getJSON('http://example.com', function(data){
//inside this function I call another api using the data response.
$.get('example.url', function(response){
//do something with this data of the response and ended function
});
// expose the data to be used by button click event hander or other
// funcitons that care about the data
webData = data;
});
}
// Set the event handler
$('#button').on('click', triggerButton);
// define the handler
function triggerButton() {
if(webData){
// do something with the webData
}else{
// display some information that tells the user the status
alert('loading...');
if(!loading){
loading = true;
loadData();
}
}
}
});
'triggerButton'ハンドラは単なる関数であり、他のすべてのJS関数と同様に通常のスコープルールを持っています。しかし、私はあなたの質問を完全に理解していません。あなたのコードは奇妙です。ボタンをクリックした後にのみAJAXリクエストをしたいですか?次に、 '$( '#button')。on( 'click'、triggerButton)'を除くすべてのコードを 'triggerButton'関数に入れてください。 – djxak
私の貧しいパラグラフの質は申し訳ありませんが、私は学びたいと思っています。 – ontiverosvzla
ボタンをクリックしたときに実際にajaxを呼びたくない場合は、Htmlの変数を変更して、華氏から摂氏への要素の温度の値を変更する必要があります。 – ontiverosvzla