使用jQuery检查环节仍然工作 [英] Use jQuery to check if links still work

查看:112
本文介绍了使用jQuery检查环节仍然工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个快速功能检查使用AJAX,看看他们是否仍然工作在页面上的每一个环节。这似乎是工作,但它增加了成功和错误类的每一位。我怎样才能得到错误回调函数只能扔,如果Ajax响应是404?

  $(礼)。每个(函数(){
    $(本)。儿童('A')。每个(函数(){
        $阿贾克斯({
            网址:$(本).attr(SRC),
            成功:$(本).addClass(成功),
            错误:$(本).addClass('错误')
        })
    })
});
 

解决方案

成功错误参数期望的功能

您就需要包装在一个匿名函数code:

  //有没有需要复杂的事情,用一个调用每一个()
$(礼>在')每个(函数(){。
    变量$这一点;
    $此= $(本); //保留提及当前链接
    $阿贾克斯({
        网址:$(本).attr(HREF),//一定要检查的权利属性
        成功:函数(){//传递一个匿名的回调函数
            $ this.addClass(成功);
        },
        错误:函数(jqXHR,状态,ER){
            //只设置404错误
            如果(jqXHR.status === 404){
                $ this.addClass('错误');
            }
            //你可以进行额外的检查与不同类别
            //其他400和500级别的HTTP状态codeS。
        }
    });
});
 

否则,你只是设置成功 $(本).addClass('成功')的返回值; ,这仅仅是一个jQuery集合。

I made a quick function to check every link on the page using AJAX to see if they still work. This seems to be working, but it's adding the success and error class to every one. How can I get the error callback function to only throw if the AJAX response is 404?

$('li').each(function(){
    $(this).children('a').each(function(){
        $.ajax({
            url:$(this).attr('src'),
            success:$(this).addClass('success'),
            error:$(this).addClass('error')
        })
    })
});

解决方案

the success and error parameters expect functions.

You'd need to wrap the code in an anonymous function:

//there's no need to complicate things, use one call to each()
$('li > a').each(function () {
    var $this;
    $this = $(this); //retain a reference to the current link
    $.ajax({
        url:$(this).attr('href'), //be sure to check the right attribute
        success: function () { //pass an anonymous callback function
            $this.addClass('success');
        },
        error: function (jqXHR, status, er) {
            //only set the error on 404
            if (jqXHR.status === 404) { 
                $this.addClass('error');
            }
            //you could perform additional checking with different classes
            //for other 400 and 500 level HTTP status codes.
        }
    });
});

Otherwise, you're just setting success to the return value of $(this).addClass('success');, which is just a jQuery collection.

这篇关于使用jQuery检查环节仍然工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆