使用jQuery检查链接是否仍然有效
我做了一个快速的function,使用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
参数期望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. } }); });
否则,你只是将success
设置为$(this).addClass('success');
的返回值$(this).addClass('success');
,这只是一个jQuery集合。
首先,您需要成功并且失败的处理程序,现在代码只针对每个链接运行。 您不需要src属性,但需要href prop。
这应该工作:
$('li').each(function(){ $(this).children('a').each(function(){ $.ajax({ url:$(this).prop('href'), success:function(){$(this).addClass('success')}, error:function(){$(this).addClass('error')} }) }) });
我也发现在每个循环中使用索引和值更优雅,所以:
$('li').each(function(){ $(this).children('a').each(function(index,value){ $.ajax({ url:$(value).prop('href'), success:function(){$(value).addClass('success')}, error:function(){$(value).addClass('error')} }) }) });
其他答案为所有错误添加了类,如果你真的想要它只有404
那么这应该做:
$(this).children('a').each(function(){ var self; self = this; //retain a reference to this $.ajax({ url:$(this).attr('src'), success: function () { //pass an anonymous callback function $(self).addClass('success'); }, statusCode: { 404: function() { $this.addClass('error'); } } }); });
您需要在function()
调用中包装成功和错误回调:
$('li').each(function(){ $(this).children('a').each(function(){ var $this = $(this); $.ajax({ url:$this.attr('href'), success: function() { $this.addClass('success'); }, error: function() { $this.addClass('error'); } }); }); });