首页 > 解决方案 > 获取未捕获的 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:

这似乎是一个时间问题,因为有时它有效,有时则无效。

标签: javascripthtmlajaxasp.net-mvc

解决方案


我发现将处理程序代码加载到 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,图像不存在,但是,网络就是网络,你永远不知道 - 至少这样我认为你可以保证找到并“修复“所有破碎的图像


推荐阅读