问题描述
我有网站,现在正在为它制作一个混合应用程序.我使用 Jquery get 方法获取我所有的博客文章.然而,问题是 <img src="/media/image.png">
有时是相对 url,有时是绝对 url.
I have website and now making a hybrid app for it.I get all my blog post using Jquery get method.However the issue is that <img src="/media/image.png">
is sometime relative url and sometime an absolute url.
每次绝对 url 破坏显示 404 错误的图像.
Everytime an absolute url breaks the image showing 404 error.
如何编写jquery函数来判断src是否为绝对值并改成
How to write Jquery function to find if src is absolute and change it to
https://www.example.com/media/image.png
我将无法提供我尝试过的任何代码示例,因为我不是前端开发人员并尝试了一整天来解决它.
I will not be able to provide any code samples I have tried since I am not a front end developer and tried whole day solving it.
注意:我只需要更改 <div id="details">
div 中的图像.
Note: I need to change images present only in <div id="details">
div.
推荐答案
您应该始终对所有图像使用相同的路径,但是就您的情况而言,您可以遍历图像并附加域,就我的用例而言在变量中添加了域,您可以根据需要更改它.
You should always use same path for all the images, but as of your case you can loop through images and append the domain, as of the use case I have added the domain in variable you can change it as per your requirement.
你可以使用常用函数或者图片onload来重新渲染,但是我h
You can use common function or image onload to rerender but I h
注意:图片加载后会重新渲染.
Note: image will rerender once its loaded.
var imageDomain = "https://homepages.cae.wisc.edu/~ece533/";
//javascript solution
// window.onload = function() {
// var images = document.getElementsByTagName('img');
// for (var i = 0; i < images.length; i++) {
// if (images[i].getAttribute('src').indexOf(imageDomain) === -1) {
// images[i].src = imageDomain + images[i].getAttribute('src');
// }
// }
// }
//jquery solution
var b = 'https://www.example.com';
$('img[src^="/media/"]').each(function(e) {
var c = b + $(this).attr('src');
$(this).attr('src', c);
});
//best approach you are using get request
//assuming you are getting this respone from api
var bArray = ["https://www.example.com/media/image.png", "/media/image.png"]
var imgaesCorrected = bArray.map(a => {
if (a.indexOf(b) === -1) {
a = b+a;
}
return a;
});
console.log(imgaesCorrected);
img {
width: 50px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="/media/image.png">
<img src="https://www.example.com/media/image.png">
这篇关于图像src相对路径到绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!