0

我有一个页面,我从维基百科加载了几张图片。维基百科图像有一个文件路径,您必须根据文件名计算该文件路径,然后您必须将其附加到以下内容:http://upload.wikimedia.org/wikipedia/commons/thumb/.

有两个问题。

  1. 在少数图片中,url 有/en/而不是/commons/',但无法知道何时。

  2. 一些链接已经过时并且不返回任何图像,给我留下了一个丑陋的容器 div。

所以我首先尝试加载图像commons并编写一些代码来检查图像是否出错。如果是这样,它将替换commonsen。然后,如果图像仍然给出错误(意味着图片根本不存在),则代码将整个 src 替换为''并隐藏 div。

所有这一切都适用于 FF,但它在 Chrome 中崩溃。我得到无穷无尽jquery.min.js:2 Uncaught RangeError: Maximum call stack size exceeded的错误。如果有人能告诉我我的代码有什么问题并帮助我修复它,我将非常感激!

这是代码:

$('#imgid').error(function()
{
   $(this).one("error", function() {
         $(this).attr('src','');$(this).parent().parent().parent().hide();
  }).attr('src', $(this).attr('src').replace("/commons/", "/en/"));

});

蒂亚!

编辑:图像周围的 html 如下所示:

<div data-id="7551400" class="pin">
<div id="sc7551400" class="scrol">
 <a class="PinIm" target="_blank" name="http://upload.wikimedia.org/wikipedia/commons/c/c0/Cage_de_Faraday.jpg" href="">
   <img class="PinImageImg" alt="" src="http://upload.wikimedia.org/wikipedia/commons/thumb/c/c0/Cage_de_Faraday.jpg/155px-Cage_de_Faraday.jpg" style="width:155px" id="img-7551400">
    </a>
       </div>
       </div>
4

2 回答 2

0

看起来您将 Chrome 置于无限循环中,试图替换 src。我会建议这样的事情:

$('img').error(function()
{  
    if(this.errorCount == undefined) this.errorCount = 0;
    if(this.errorCount < 1){
        var newSource = $(this).attr('src').replace("/en/", "/commons/");
        $(this).attr('src', newSource);
     }
    if(this.errorCount == 1){
        $(this).parents('div').hide();
    }

    this.errorCount++;
});

这会将错误计数设置为 0,并且在第一次通过后它将隐藏 div。如果需要,您可以使用它来完成几个选项。

这是一个小提琴,我将 commons 更改为 common,所以它会出错两次,第二次通过 div 被隐藏:http: //jsfiddle.net/davidstetler/uvKvC/

于 2013-03-05T21:14:16.127 回答
0

这可能是因为attr('src', $(this).attr('src'...

尝试这个:

$('#imgid').error(function()
{
   var src = $(this).attr('src');
   $(this).one("error", function() {
      $(this).attr('src','');
      $(this).parents('.pin').hide();
   }).attr('src', src.replace("/commons/", "/en/"));
});
于 2013-03-05T20:20:23.123 回答