捕获参考错误:函数未定义

时间:2019-09-24 22:35:18

标签: javascript html ajax asp.net-mvc

在我看来,我正在显示图片:

<img src="https://some-host/img1.jpg" onerror="showNoPhotoIcon(this);">

我已经在名为common.js的单独文件中定义了函数showNoPhotoIcon

/*========== 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:

收到错误后,我尝试确认该函数是否已定义=>正确。

enter image description here

Update2:

这似乎是一个计时问题,因为有时它可以工作,有时却不可以。

3 个答案:

答案 0 :(得分:1)

我发现在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,如果是,则在附加错误处理程序后“重新加载”图像

在我看来,这有点怪诞,您还可以假设宽度为0表示图像不存在,但是,网络就是网络,您永远不会知道-至少这样,我认为您一定可以找到并“修复”所有损坏的图像

答案 1 :(得分:0)

可接受的答案说明了以下问题:发生错误时未加载错误处理程序。

就我而言,我将处理程序更改为使用内联js:

<img src="https://some-host/img1.jpg" onError="this.onerror=null; this.src='/images/no-photo-icon.jpg';"

答案 2 :(得分:-1)

您的代码看起来不错,也许是您的script标记中的网址。尝试在同一个html页面中运行您的函数以进行仔细检查。我没有任何理由设置image.onerror = "";return true;

最好的方法应该是将事件监听器应用于一个或多个图像,这样就不必在html标记中编写函数。

document.querySelectorAll('img').forEach(image =>{
     image.addEventListener('error', (e) =>{
          // load the placeholder image
     });
});