我制作了一个快速功能,使用 AJAX 检查页面上的每个链接,看它们是否仍然有效。这似乎可行,但它正在为每个人添加成功和错误类。如何让错误回调函数仅在 AJAX 响应为 404 时抛出?
$('li').each(function(){
$(this).children('a').each(function(){
$.ajax({
url:$(this).attr('src'),
success:$(this).addClass('success'),
error:$(this).addClass('error')
})
})
});
最佳答案
success
和 error
参数需要函数。
您需要将代码包装在匿名函数中:
//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/