Jquery错误方法未显示所需结果

时间:2013-02-26 08:07:17

标签: jquery

<img src="one.jpg" height="200" width="200">            
<img src="three.jpg" height="200" width="200"><br>      

<a href="mylink.html"><u> Click Here  </u></a><br>      

<script src="displayAlert.js"></script>             

<style type="text/css" src="externCSS.css"> </style> 


$(document).ready(function(){
   $("[src]").error(function(){
        alert ("error");
      });
});

预期输出 - 当指定路径中不存在文件时,代码应显示警报。

仅当图像文件不在指定路径时,jquery才会显示警报。如果css或脚本文件不存在,它不会显示任何内容。我哪里错了?

2 个答案:

答案 0 :(得分:0)

尝试

$("img")
.error(function(){
$(this).hide();
})
.attr("src", "missing.png");

检查是否为DOM使用定义了attr。

var attr = $(this).attr('src');
// `attr` is false.  Check for both.
if (typeof attr !== 'undefined' && attr !== false) {
    //code goes here
}

传递多个选择器

$(window).load(function()
{
    $('script,img,link').each(function()
    {
        var attr = $(this).attr('src');
        // `attr` is false.  Check for both.
        if (typeof attr !== 'undefined' && attr !== false)
        {
            //code goes here
        }
    });
});

答案 1 :(得分:0)

这是用jQuery jQuery error

写的
  

在浏览器触发错误之前,必须附加事件处理程序   event,这就是为什么示例在附加后设置src属性的原因   处理程序。此外,错误事件可能无法正确触发   页面在本地提供;错误依赖于HTTP状态代码和意志   如果URL使用文件:protocol。

,通常不会被触发

这意味着您必须在页面加载完成之前附加处理程序。 我认为这是你的问题。

这是jQuery示例代码:

$('#book')
    .error(function() {
    alert('Handler for .error() called.')
}).attr("src", "missing.png");

如果您正在寻找可立即使用的解决方案,我建议:

<img url="one.jpg" height="200" width="200"> 
<img url="three.jpg" height="200" width="200"><br>

<a href="mylink.html"><u> Click Here  </u></a><br>

<script url="displayAlert.js"></script>
<script src="jquery.min.js"></script>

<style type="text/css" url="externCSS.css"> </style>

<script>
   $("[url]").each ( function () {
        $(this).error (function () {
            alert ( "Error" );
        }).attr ( 'src',  $(this).attr ("url"));
    });
</script>
相关问题