javascript - 使 HTML 按钮的显示属性依赖于 jQuery Get() 的完成
问题描述
再会!
我在编写一个我一直在摆弄的扩展时遇到了一个有趣的问题——根据 jQuery get()函数中的“if 语句”显示/隐藏特定按钮。由于该函数的加载时间比按钮和其他元素的加载时间长,因此当调用由 jQuery get()结果定义的变量以确定按钮显示(块或无)时,它返回 undefined。我想到的几种解决方案是可能的setTimeout()在x秒 后获取值,但这种方法不可行,因为显示应该取决于 get 语句的完成(成功或失败),类似于onload是到 html 正文。
有任何想法吗?
解决方案
创建一个具有回调的 Promise,该回调将在请求完成后调用您的函数。有关 Promise 的更多信息,请参阅Mozilla Docs。
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff.
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc so check the status.
if (req.status == 200) {
// Resolve the promise with the response text.
resolve(JSON.parse(req.response));
}
else {
// Otherwise reject with the status text which will hopefully be a meaningful error.
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request.
req.send();
});
let promiseUrl = 'yoururlhere';
get(promiseUrl).then(function(response){
displayButton(response);
}, function(error) {
console.error("Failed!", error);
})
推荐阅读
- sql - 我如何添加表的以下三个字段的值并将其存储到 DB2 查询中的用户定义字段中
- c# - 标签应该打开一个新窗口,但它不适用于ieDriver
- vue.js - 设置自定义编辑器显示 kendoDropDownList 不是函数
- c++ - 运行代码时出现 C++ 编译器错误(seg fault core dumped)
- javascript - 在vue js中显示和隐藏框onclick
- javascript - 如果应用程序部署在集群上,则重复的 html 元素
- operating-system - MMU如何获取中断向量的物理地址?
- php - PhpMailer 不在邮件正文中嵌入图像但附加
- javascript - 如何在 WebStorm 的外部库中加载 jQuery?
- mysql - 如何添加在同一个表中选择的临时列?