[英]How can I retrieve image error code using JavaScript or jQuery?
I am changing the src
attribute of an image element.我正在更改图像元素的
src
属性。 If there's an error I want to know the error status code.如果出现错误,我想知道错误状态代码。
You could adapt this source example on mdn web docs.您可以在 mdn web 文档上改编此源代码示例。 If you change the
src
attribute programmatically and need to check first if it gives an error code, it could do the job.如果您以编程方式更改
src
属性并且需要首先检查它是否给出错误代码,它可以完成这项工作。 Here a draft, I hope this is going to help you.这是草稿,希望对您有所帮助。
let changesrc = (newsrc) => { const myImage = document.getElementById('testimg'); const myRequest = new Request(newsrc); fetch(myRequest).then((response) => { console.log(response.status); if(response.status == "200") { response.blob().then((myBlob) => { const objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; }); } }); };
<button onclick="changesrc('https://picsum.photos/200');">test ok</button> <button onclick="changesrc('https://picsum.photos/noway');">test not ok</button> <img id='testimg' src="https://picsum.photos/200">
You can use Image API in Javascript, for know when image load fail:您可以使用 Javascript 中的图像 API,了解图像加载失败的时间:
function mountImage(src) {
const img = new Image();
img.src = src;
img.onload = () => {
// image loaded
}
img.onerror = () => {
// image fail load
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.