1

我的脚本在表格中附加了一些代码来加载图像。但是,它会根据表的内容解释图像链接。这有时会导致它加载错误图像。我创建了一个占位符图像,如果第一个图像失败,则会加载该图像,但是如果该占位符无法加载,则脚本将进入无限循环。

$(document).ready(function() {
    $('tr[id^="mini"]').each(function(index) {
        var s = $(this).find('td:first');
        var product = s.text().replace(/\s+/g, '');
        s.append('<br><a href="/-p/' + product + '.htm" target="_blank">View Live</a><br><a title="Click for bigger image" href="/PhotoDetails.asp?ShowDESC=Y\&amp;ProductCode=' + product + '" onclick="window.open(\'/PhotoDetails.asp?ShowDESC=Y\&amp;ProductCode=' + product + '\',\'Option\',\'scrollbars=yes,menubar=no,status=no,location=no,width=600,height=640\'); return false;" target="_blank"><img src="/v/vspfiles/photos/' + product + '-0.jpg" border="0" style="max-width:150px;max-height:150px" id="monkey-inserted-image" /></a>');
    });
    // This checks for images that do not load //
    $('img#monkey-inserted-image').error(function() {
        $(this).removeAttr("id").attr("src", "/tamper/noimage1.png");
        // If this image fails to load, an infinite loop is created //
    });
});

我尝试使用 .removeAttr() 希望这会停止循环,但事实并非如此。

4

4 回答 4

3

你为什么不期待这个?你基本上是在告诉它每次失败时再试一次,所以很明显,如果src它不好,那么它每次都会失败。

removeAttr()不会做你认为它做的事。该error事件已注册,如果您尝试取消注册,则需要以不同的方式进行。

也许像这样:

$(this).unbind('error');
于 2012-12-13T09:56:59.403 回答
2

设置占位符时需要取消注册error处理程序:

$('img#monkey-inserted-image').error(function() {
    $(this).unbind("error").attr("src", "/tamper/noimage1.png");
    // No more infinite loop :-)
});
于 2012-12-13T09:58:14.240 回答
0

处理错误时,您应该取消绑定该事件,以便在替换图像未加载时它不会无限触发

$('img#monkey-inserted-image').on('error', function() {
        $(this).off('error').attr("src", "/tamper/noimage1.png");
        // If this image fails to load, an infinite loop is created //
    });
于 2012-12-13T09:57:57.190 回答
0

无限循环是“正常的”。您正在侦听图像上的错误事件,因此如果您的默认占位符图像触发错误,则会调用您的函数并再次尝试放置该占位符图像,以便触发错误事件并再次尝试放置占位符.. . 嗯,我想你明白了。

您可以检查src图像的属性。如果您已经在处理占位符图像,则什么也不做(或后备)。

$('img#monkey-inserted-image').error(function() {
    if ($(this).attr('src') == '/tamper/noimage1.png')) {
        // Do your fallback here
        return;
    }

    $(this).removeAttr("id").attr("src", "/tamper/noimage1.png");
    // If this image fails to load, an infinite loop is created //
});
于 2012-12-13T09:57:58.897 回答