如何在url中检测404错误,然后使用Jquery将url图像设置为display:none

时间:2010-08-26 08:19:58

标签: javascript jquery

我有一个表重复每行数据的文件下载的图像链接。我想使用Jquery或Javascript来检测图像链接是否返回404错误,这意味着它尝试查找的文件不存在,然后将图像链接设置为 display:none 以使其隐藏。

非常感谢任何帮助!

杰米。

--- ---编辑

这是我的网址,如果找不到.igs文件

,则需要将其设置为隐藏

<a href="/path/to/file.igs"><img src="pic.jpg" alt="My Image Link"></a>

不幸的是我无法利用服务器端处理。

3 个答案:

答案 0 :(得分:4)

您可以使用error()事件处理程序:

$("img").error(function () {
    $(this).css("display", "none");
});

<小时/> 我看到我们中的一些人误解了你的原始问题,你的编辑清除了一点。只有使用AJAX才能实现您想要的效果。只需要请求文件的标题即可:

// Find all <a> tags where href ends with .igs, hide and loop over them 
$("a[href$=.igs]").hide().each(function (i, el) {
    $.ajax({
        type: "HEAD",
        url: el.href,
        success: function () {
            // Success, we can unhide the element.
            el.show();
        }
    });        
});

当然,如果文件位于其他域上,则无法使用。此外,如果有很多客户端和服务器,这对于客户端和服务器来说都是非常昂贵的过程。

答案 1 :(得分:1)

你也可以使用这个技巧,

$('img').hide().load(function(){
    $(this).show();
});

这将隐藏所有图像,然后在完全加载时显示它。

答案 2 :(得分:1)

或者你可以使用Reigel&amp; amp;提供的两个答案的组合。 Andy E,通过在发生错误时显示额外的图像...

.downloadedImage, .downloadFailed { display:none; }

<table>
    <tr>
        <td>
            <img class="downloadedImage" src="imageUrl1.jpg"/>
            <img class="downloadFailed" src="downloadFailed.jpg"/>
        </td>
    </tr>
    <tr>
        <td>
            <img class="downloadedImage" src="imageUrl2.jpg"/>
            <img class="downloadFailed" src="downloadFailed.jpg"/>
        </td>
    </tr>
    <tr>
        <td>
            <img class="downloadedImage" src="imageUrl3.jpg"/>
            <img class="downloadFailed" src="downloadFailed.jpg"/>
        </td>
    </tr>
</table>

$("img.downloadedImage").load(function(){
    $(this).show();
}).error(function(){
    $(this).next().show();
});

这里要注意的重要事项(如果我的想法是正确的)是jQuery执行的时间。如果它运行得太快,则DOM元素将无法为它们分配事件处理程序 - 如果它运行得太晚,事件处理程序将在事件发生后附加。您可能需要尝试将jQuery代码段放在页面末尾并将其放在$(document).ready处理程序中。

更新快速实验表明,脚本代码段在页面末尾(或在表定义之后)表现最佳,而在$(document).ready处理程序中表现最佳。