【发布时间】:2017-03-29 15:37:11
【问题描述】:
我有一个包含一些报告图片的页面。在每张图片下,有 4 个按钮可以在点击时更改图片的 src。 我编写了一个简短的脚本 (imageValidation.js) 来检查图像是否已成功加载,如果没有,则运行一个函数,将图像 src 更改为通用的“找不到文件”图片。
问题是我希望脚本在页面最初加载时替换“损坏的”图像 srcs,但事实并非如此。但是,当我通过单击按钮更改图片时,脚本可以正常工作。
举个例子,我删除了 01UR(All).jpeg。当页面加载时,我看到通用的破损图片图标。但是当我点击 All Cycles 按钮时,图像会根据需要更改为 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';
}
【问题讨论】:
标签: javascript