我有一个页面,其中包含一些报告图片。在每个图像下,有 4 个按钮,单击时可以更改图像的 src。 我编写了一个简短的脚本 (imageValidation.js),用于检查图像是否已成功加载,如果没有,则运行一个将图像 src 更改为通用“文件未找到”图片的函数。
问题是我希望脚本在页面最初加载时替换“损坏的”图像 src,但事实并非如此。但是,当我通过单击按钮更改图片时,脚本工作正常。
举个例子,我删除了01UR(All).jpeg。当页面加载时,我看到通用损坏的图片图标。但是,当我单击所有周期按钮时,图像会根据需要更改为ReportUnavailable.jpeg。
我尝试执行正文部分的 onload 属性中的代码。还尝试将脚本标记移动到头部和正文部分的开头。
应该如何正确完成?
这是 HTML:
<body>
<div>
<img id="UR_chart" class="Reportpicture" src="reports/01UR(All).jpeg" />
</div>
<div class="submenu">
<button id="UR_all" onclick="changeChart('UR_chart', 'reports/01UR(All).jpeg')">
All Cycles
</button>
<button id="UR_c1" onclick="changeChart('UR_chart', 'reports/01UR(C1).jpeg')">
Cycle 1
</button>
<button id="UR_c2" onclick="changeChart('UR_chart', 'reports/01UR(C2).jpeg')">
Cycle 2
</button>
<button id="UR_c3" onclick="changeChart('UR_chart', 'reports/01UR(C3).jpeg')">
Cycle 3
</button>
</div>
<!-- more divs -->
<script src="../Scripts/imageValidation.js"></script>
</body>
图像验证脚本:
/*imageValidation.js*/
var reportPix = document.getElementsByClassName("Reportpicture");
for(var i = 0; i < reportPix.length; i++)
{
reportPix[i].addEventListener("error", noImageFound);
}
function noImageFound()
{
this.src = 'ReportUnavailable.jpeg';
}
最佳答案
我在这里做两件事。 在 window.onload 之后,检查所有图像,如果它们的 natrualWidth 和 naturalHeight 为 0,则将替换它们。这应该处理在事件注册之前加载的所有图像。
事件监听器仍然注册,并且在图像更改的情况下将被调用。
function changeChart() {
reportPix[0].src = "blank1.gif";
}
window.onload = checkImages;
var reportPix = document.getElementsByClassName("Reportpicture");
for(var i = 0; i < reportPix.length; i++) {
reportPix[i].addEventListener("error", noImageFound);
}
function checkImages() {
for(var i = 0; i < reportPix.length; i++) {
if (reportPix[i].naturalHeight === 0 && reportPix[i].naturalWidth === 0) {
noImageFound(reportPix[i]);
}
}
}
function noImageFound(obj) {
if (obj.target) {
obj.target.src = "https://img.clipartfest.com/cee7c57a2d96b3117b12d85fc6b6d6fc_photo-not-available-large-picture-not-available-clipart_325-384.png";
} else {
obj.src = "https://img.clipartfest.com/cee7c57a2d96b3117b12d85fc6b6d6fc_photo-not-available-large-picture-not-available-clipart_325-384.png";
}
}
<div>
<img id="UR_chart" class="Reportpicture" src="reports/01UR(All).jpeg" />
</div>
<div class="submenu">
<button id="UR_all" onclick="changeChart('UR_chart', 'reports/01UR(All).jpeg')">
All Cycles
</button>
<button id="UR_c1" onclick="changeChart('UR_chart', 'reports/01UR(C1).jpeg')">
Cycle 1
</button>
<button id="UR_c2" onclick="changeChart('UR_chart', 'reports/01UR(C2).jpeg')">
Cycle 2
</button>
<button id="UR_c3" onclick="changeChart('UR_chart', 'reports/01UR(C3).jpeg')">
Cycle 3
</button>
</div>
关于javascript - 页面加载时错误事件监听器不执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43098047/