为了在页面加载后立即设置事件处理程序,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响应分别接收之前和之后 click事件。如果您在接收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...
});
});
});
此外,如果你想要的API请求点击按钮后发送,您可以移动它们的事件处理中(这里使用另一个函数以使其更清晰):
$(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();
}
}
}
});