【问题标题】:rewriting a function to a boolean将函数重写为布尔值
【发布时间】:2019-09-16 18:17:35
【问题描述】:

大家好,我有这个功能: 它检查图像 URL 是否是实际图像,但我想更改它,而不是控制台日志,我希望它返回 true 或 false,

function checkImage(url) {
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.send();
  request.onload = function() {
    status = request.status;
    if (request.status == 200) //if(statusText == OK)
    {
      console.log("image exists");
    } else {
      console.log("image doesn't exist");
    }
  }
}
checkImage("https://picsum.photos/200/300");

我希望 checkImage 返回 True/False 而不是控制台日志记录,但是当我写 return true 或 false 时,这似乎不起作用, 谁知道为什么?

【问题讨论】:

  • 在 HTTP 请求完成之前,.onload 函数实际上不会被调用,这将在 checkImage() 返回之后很久。
  • 所以我应该异步执行?
  • 您在什么情况下尝试使用 checkImage 功能?
  • @Tekill 我正在创建一个网站,当用户可以将图像添加到他们的个人资料时,我想检查图像是否存在,然后显示它或者如果不存在则放置默认图片。

标签: javascript image


【解决方案1】:

只需将控制台更改为回调可能会帮助您解决它

function checkImg(url,success,error){
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.send();
request.onload = function() {
status = request.status;
if (request.status == 200) //.if(statusText == OK)
{
  success && success()
} else {
  error && error()
}

} }

用 Image.onload() 替换 Ajax

【讨论】:

    【解决方案2】:

    如果此函数的全部目的是检查图像是否存在以显示默认图像,我会使用更简单的方法。为什么不使用以下方法:

    <img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
    

    这有更详细的描述here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-09
      • 2012-05-13
      • 2011-12-31
      • 2014-09-03
      • 1970-01-01
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多