我创建了一个快速功能,使用 AJAX 检查页面上的每个链接,看看它们是否仍然有效。这似乎有效,但它为每个类添加了成功和错误类。如何让错误回调函数仅在 AJAX 响应为 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
参数期望函数。
您需要将代码包装在匿名函数中:
//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 集合。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)