html button 触发另一个 button jauery,使用jQuery在另一个API调用中调用API

为了在页面加载后立即设置事件处理程序,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();

}

}

}

});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值