javascript - 获取未捕获的 ReferenceError:未定义函数
问题描述
在我看来,我正在展示一张图片:
<img src="https://some-host/img1.jpg" onerror="showNoPhotoIcon(this);">
我showNoPhotoIcon
在一个名为 common.js 的单独文件中定义了该函数
/*========== when image is not available ==========*/
function showNoPhotoIcon(image) {
image.onerror = "";
image.src = '/images/no-photo-icon.jpg'
return true;
}
我从我的视图中引用 common.js,以下行位于我视图的最底部(html 页面)
<script src="/Scripts/app/common.js"></script>
但是从视图中无法访问该函数,当图像丢失时,代码尝试调用showNoPhotoIcon
函数并且我收到以下错误:
未捕获的 ReferenceError:未定义 showNoPhotoIcon
更新1:
收到错误后,我尝试确认该函数是否已定义 => 它是。
更新2:
这似乎是一个时间问题,因为有时它有效,有时则无效。
解决方案
我发现将处理程序代码加载到 body 元素底部的外部 JS 中会导致错误处理不一致 - 但这就是你想要 JS 代码的地方,我同意,所以......
使错误处理一致的一种方法如下
首先,不要使用 onerror 属性
<img src="https://some-host/img1.jpg" alt="" />
其次,更改showNoPhotoIcon
如下,因为它将以错误事件作为参数调用 - 这removeEventListener
很容易
function showNoPhotoIcon(e) {
const image = e.target;
image.removeEventListener('error', showNoPhotoIcon);
image.src = '/images/no-photo-icon.jpg'
}
在 common.js 中添加此代码
document.querySelectorAll('img').forEach(img => {
if (img.naturalWidth === 0) {
img.addEventListener('error', showNoPhotoIcon);
img.src = img.src;
}
});
这将检查图像宽度是否为 0,如果是,则在附加错误处理程序后“重新加载”它
在我看来这有点 hacky,你也可以假设如果宽度为 0,图像不存在,但是,网络就是网络,你永远不知道 - 至少这样我认为你可以保证找到并“修复“所有破碎的图像
推荐阅读
- java - 如何使用 GPSShell 在 Java 卡上上传小程序
- prestashop - prestashop 1.7 public function renderAddForm() 保存类别名称和id
- microsoft-graph-api - 将 Azure B2B 用于我们的客户门户
- reactjs - 通过 useSelector 渲染项目列表哪个更高效?
- android - Kotlin:从 SD 卡中的文件夹中读取所有文件
- python - 传递值的形状是 (492, 7),索引意味着 (1, 7) 用于财务数据
- crystal-reports-2010 - Crystal报告如何获取符号右侧的数字(这是带有2位小数和千位分隔符的字符串)=
- reactjs - 组件重叠 - 显示一个在另一个之上 - 反应路由器 v5
- flutter - Flutter Unhandled Exception:接收数据时连接关闭
- node.js - GPU.js计算多对象xyz之间的距离?