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

标签 javascript jquery ajax 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')
        })
    })
});

最佳答案

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.
        }
    });
});

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

关于javascript - 使用 jQuery 检查链接是否仍然有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13310029/

相关文章:

javascript - 如何通过 JavaScript 检测键盘修饰符(Ctrl 或 Shift)

javascript - 如何在php中创建一个自动任务?

javascript - Nightwatch - 在导航栏中抓取嵌套按钮

javascript - 将对象作为 POST 变量从 jquery 传递到 php

javascript - API ajax 请求的进度条仅在从 API 获得响应后才开始加载

javascript - 设置内容类型后发送后无法设置 header

javascript - 使用 WebRTC/替代方案的点对点 1080p 直播?

jquery - 在 jQuery 1.9 中使用事件命名空间时,感叹号在 trigger() 中不起作用

javascript - 将 jQuery 回调函数保存在单独的文件中

php - ajax加载mysql数据到多个div