使用jQuery检查链接是否仍然有效

Thr*_*ead 6 javascript ajax jquery http-status-code-404

我做了一个快速的功能,使用AJAX检查页面上的每个链接,看看它们是否仍然有用.这似乎有效,但它正在为每一个添加成功和错误类.如果AJAX响应是404,我怎样才能使错误回调函数抛出?

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

zzz*_*Bov 6

successerror参数期望的功能.

您需要将代码包装在匿名函数中:

//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.
        }
    });
});
Run Code Online (Sandbox Code Playgroud)

否则,您只需设置success返回值$(this).addClass('success');,这只是一个jQuery集合.