I am trying to check a link (that I know if unavalable 50% of the time, but at random times) to see if it returns a 200 HTTP Status code. If so I want to change the class on the link from offline to online.
Desired process: get all links that point to ip addresses, give them class Offline, for each do a request to YQL, if a 200 code is received change class to Online.
Currently I have this:
var streams = $('article a[href^="http://65"]');
streams.addClass("offline");
streams.each(function (){
destination = $(this).attr("href");
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=use%20%22store%3A%2F%2FtbYorcb2jIkiHPcRbkpSUG%22%20as%20HTTPStatus2%3B%20select%20status%20from%20HTTPStatus2%20where%20url%3D%22"+ encodeURIComponent(destination) +"%22&format=json&callback=",
function(data){
var httpstatus = data.query.results.result.status;
if(httpstatus == 200){
console.log('If = 200');
changeStatus();
}
}
);
function changeStatus(){
console.log('changeStatus called');
$(this).removeClass("offline").addClass("online");
};
//$(this).removeClass("offline").addClass("online");
});
This all seems to work apart from the changeStatus function. I thought that by putting it outside the AJAX request in a seperate function it would work, but it doesn’t.
It looks like the problem is the $(this) reference which isn’t right. However if I put the same statement outside of a function (as commented out in the code above), it works fine.
Any help / pointers would be much appreciated.
when you use $(this) inside of your changeStatus function, the this identifier refers to the changeStatus function object, not the current stream being iterated. You need to pass the object in, or move changeStatus into the other function.
You’re also missing a “var” on your destination variable.
Edit: some help with the “this” keyword: http://jqfundamentals.com/#example-2.40