开发者

Using JQuery and Ajax to test status of links

I'm writing a script which tests if any links within a particular div 404.

Outline:

  1. Iterate through links with jquery .each()
  2. Test status of link with ajax
  3. Add either a "linkSuccess" or "linkFail" class to the link.

The fun开发者_如何学Cction is successfully testing the URLs but I can't seem to apply a class to the link. I'm guessing I have a scope problem.

Code

function testLinks() { 
$('.editor a').each(function(i)  {
    var thisUrl = $(this).attr('href');

    $.ajax({
        url: thisUrl, 
        type: 'get',
        method: 'get',
        error: function() {
            $(this).addClass('linkFail');
        },
        success: function() { 
            $(this).addClass('linkSuccess');
        }
    }); 

});

}

How do I get the ajax portion of the function to recognize the link element?


in the ajax call $(this) is not $j('.editor a') anymore try:

function testLinks() { 
$('.editor a').each(function(i)  {
    var thisUrl = $(this).attr('href');

    var element = $(this); 

    $.ajax({
        url: thisUrl, 
        type: 'get',
        method: 'get',
        error: function() {
            element.addClass('linkFail');
        },
        success: function() { 
            element.addClass('linkSuccess');
        }
    }); 

});


I think this is because $(this) in the success callback of the ajax call is no longer the a element grabbed by the selector in the first step. Try copying $(this) to a local variable before firing off the ajax call.


$(this) is referring to the ajax element. I think $(this).parent().addClass('linkFail') should work.

http://api.jquery.com/parent/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜