如果加载页面时图片出现问题,我会尝试更改某些 img
标记的 src
。我似乎遇到了一些随机行为,特别是来自 Internet Explorer 9。有些图像正确显示了替换的图像,有些图像上有红十字。如果我在浏览器中调试,我会被告知 ImgError()
未定义。它在代码中定义得很清楚并且显然是有效的。为什么会出现这种情况?
<div class="PhotoBorder"><img alt="" onerror="imgError(this)"
src="./images/services/69_Staffmember.jpg" /></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
$(window).load( function() {
$('.RowWrapper').each(function() {
var TotalWidth = 0;
$(this).find('.StaffMember').each(function() {
TotalWidth = TotalWidth + $(this).outerWidth(true);
});
this.style.width = TotalWidth + "px";
});
});
function imgError(img)
{
img.setAttribute("src","./images/services/49_ImgMissing.jpg");
img.removeAttribute("onerror");
}
</script>
最佳答案
首先,如果您收到错误 ImgError() is not defined
这是因为你的函数名称是 imgError
,不是ImgError()
。
但是,如果这是您问题中的拼写错误,那么您可能会收到错误 imgError() is not defined
在某些时候,因为很可能正在从缓存中请求图像,并且它的错误处理程序会立即触发 - 即在解析文档的其余部分之前,这意味着您的 imgError
功能尚不可用。要修复它,只需输入 imgError
函数位于文档头部的脚本标记中。
关于javascript - 使用 Javascript 即时更改图像 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752133/