我的脚本将一些代码附加到表中以加载图像。但是,它会根据表的内容解释图像链接。这有时会导致它加载错误的图像。我创建了一个占位符图像,如果第一个图像失败,则会加载该占位符图像,但是如果此占位符无法加载,则脚本将进入无限循环。
$(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\&ProductCode=' + product + '" onclick="window.open(\'/PhotoDetails.asp?ShowDESC=Y\&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() 希望这会停止循环,但事实并非如此。
最佳答案
为什么你不希望这样呢?您基本上是在告诉它每次失败时重试,因此显然如果 src
不好,那么它每次都会失败。
removeAttr()
不会执行您认为它会执行的操作。 error
事件已注册,如果您尝试取消注册它,则需要采用不同的方式。
也许像这样:
$(this).unbind('error');
关于jquery - 当替换图像未加载时,img 元素上的错误(函数)导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13857176/