首页 > 解决方案 > 使 HTML 按钮的显示属性依赖于 jQuery Get() 的完成

问题描述

再会!

我在编写一个我一直在摆弄的扩展时遇到了一个有趣的问题——根据 jQuery get()函数中的“if 语句”显示/隐藏特定按钮。由于该函数的加载时间比按钮和其他元素的加载时间长,因此当调用由 jQuery get()结果定义的变量以确定按钮显示(块或无)时,它返回 undefined。我想到的几种解决方案是可能的setTimeout()在x秒 后获取值,但这种方法不可行,因为显示应该取决于 get 语句的完成(成功或失败),类似于onload是到 html 正文。

有任何想法吗?

标签: javascripthtmljquerycss

解决方案


创建一个具有回调的 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);
})

推荐阅读