简体   繁体   English

如何在JS中为图像指定两个可能的文件路径?

[英]How can I specify two possible file paths for an image in JS?

I've done a few searches on this via Google and the Stack Overflow search bar, and nothing relevant shows up. 我已经通过Google和Stack Overflow搜索栏对此进行了一些搜索,但没有显示任何相关信息。 I'm not even sure if this is possible, so let me know if it isn't. 我什至不确定这是否可行,所以请告诉我是否可行。 What I'm looking for is a way to set two possible file paths for an image (SVG file) for an icon, such that if the image isn't at the first file path/location, it'll try the second. 我正在寻找一种为图标的图像(SVG文件)设置两个可能的文件路径的方法,这样,如果图像不在第一个文件路径/位置,它将尝试第二个。 I have an object like so: 我有一个像这样的对象:

this.bookmarkButtonConfig = {
    "oc-control": "BookmarkButton",
    "label": "BookmarkButton",
    "group": "primary",
    "action": "onBookmark",
    "buttonType": "toggle",
    "image": "$MODULE_PATH/images/favorite-icon.svg"
}

All of these properties are then being read by something else and configuring a button based on said properties, but that's not important for this. 然后,所有其他属性都将被所有其他属性读取,并根据所述属性配置按钮,但这并不重要。 Is there a way that I can set the "image" so that it'll look for the icon at one file path, and then if it's not there, it'll try a second file path? 有没有一种方法可以设置"image"以便它在一个文件路径中查找该图标,然后如果不存在,则尝试另一个文件路径? Is there some sort of function or method that could do this? 是否有某种功能或方法可以做到这一点?

Thanks for any help! 谢谢你的帮助!

Yes you can using an AJAX call to check if the image exists in the server, first write this function: 是的,您可以使用AJAX调用来检查服务器中是否存在映像,请首先编写以下函数:

function imageExists(url){
    var http = new XMLHttpRequest();

    http.open('HEAD', image_url, false);
    http.send();

    return http.status != 404;
}

Then assign the url depending on the result like this: 然后根据如下结果分配URL:

var src = imageExists(the first url) ? "the first url" : "the second url";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM