爲了在頁面加載後立即設置事件處理程序,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();
}
}
}
});
'triggerButton'處理函數只是一個函數,它與所有其他JS函數一樣具有正常的作用域規則。但我不完全瞭解你的問題。你的代碼很奇怪。只有在點擊按鈕後纔想發出AJAX請求?然後,只需將除$('#button')。on('click',triggerButton)'之外的所有代碼放入'triggerButton'函數即可。 – djxak
我很抱歉我的段落質量差,我正在努力學習。 – ontiverosvzla
我不想在單擊按鈕時實際調用ajax,我只是想在Html中更改一個變量,具體將元素中的溫度值從華氏溫度改爲攝氏溫度,反之亦然。 – ontiverosvzla