Jquery error() 在 Chrome 和 IE 中可以工作,但在 Firefox 中无法工作

4
我正在尝试弄清楚为什么这个jQuery在Chrome和IE中正常工作,但在Firefox中不起作用。它应该做的事情(并且在Chrome和IE中确实如此)是循环遍历ul中的每个li,并查看IMG src是否会引发错误。如果是,那么就删除li。
$('ul.community-properties li').each(function() {
    $('li IMG').on('error', function() {
       $(this).parent().remove();
    });
});

我也尝试过

$('ul.community-properties li').each(function() {
    $('li IMG').error(function() {
        $(this).parent().remove();
    });
});

如果有更高效的方法或者能在所有浏览器中运行的方法就太好了。

这是HTML结构:

<ul class="community-properties">
    <li>
     <img src="{tag_community property1_value}" />
     <div class="item-link"><a href="{tag_community property1 url}">View Property Details</a></div>
    </li>
    <li>
     <img src="{tag_community property2_value}" />
     <div class="item-link"><a href="{tag_community property2 url}">View Property Details</a></div>
    </li>
    <li>
     <img src="{tag_community property3_value}" />
     <div class="item-link"><a href="{tag_community property3 url}">View Property Details</a></div>
    </li>
    <li>
     <img src="{tag_community property4_value}" />
     <div class="item-link"><a href="{tag_community property4 url}">View Property Details</a></div>
    </li>
</ul>

你什么时候绑定它? - epascarello
你在浏览器控制台中有收到任何错误信息吗? - j08691
1
你其实不需要使用 each,事实上它内部的 li IMG 选择器非常低效,因为它会每次都在 DOM 中针对每个包含图像的 li 进行目标定位。 - Rooster
不行,用Firebug检查了一下,什么也没得到。当我在Firefox中检查代码时,它显示事件正在运行,但由于某种原因它没有执行错误函数中的代码。 - Action Coding
@Rooster,如果没有使用each,我该如何循环遍历ul中的所有li? - Action Coding
显示剩余2条评论
1个回答

2

检查图片是否已加载

window.setTimeout( function() { //added delay to make sure that onerror already has run. 

$('ul.community-properties li img').one('error', function() {  //bind the error event to the images
    $(this).parent().remove();
}).filter( function() {  //check to see if an image was loaded from the cache as broken (or if onerror fired before set)
    return (this.complete && (this.naturalWidth===0 || this.naturalWidth===undefined));  
}).trigger("error");  //fire the error event


},1000);  //Broken images should hide after one second
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul class="community-properties">
    <li>
     <img src="{tag_community property1_value}" />
     <div class="item-link"><a href="{tag_community property1 url}">View Property Details</a></div>
    </li>
    <li>
     <img src="http://i.imgur.com/UyY6HH5.gif" />
     <div class="item-link"><a href="{tag_community property2 url}">View Property Details</a></div>
    </li>
    <li>
     <img src="{tag_community property3_value}" />
     <div class="item-link"><a href="{tag_community property3 url}">View Property Details</a></div>
    </li>
    <li>
     <img src="{tag_community property4_value}" />
     <div class="item-link"><a href="{tag_community property4 url}">View Property Details</a></div>
    </li>
</ul>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接