-1

还在学习中,需要一些帮助。

此代码示例检查 url 的有效性:

function check_URL() {
var url = "http://" + localStorage['t'] + ".somewhere.com";

$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
            "q=select%20*%20from%20html%20where%20url%3D%22"+
            encodeURIComponent(url)+
            "%22&format=xml'&callback=?",
    function(data){
      if(data.results[0]){
        console.log("yes");
      } 
      else { 
      console.log("no");
      alert(url + " is not a valid URL or is down.");

     }
    }
  );

};

它完全符合我的要求(我在这里找到了它!)。但是,我也需要检查其他网址。

我怎么能用 .each 做到这一点?我对这些东西太陌生了,一个例子将有助于我的学习。

此外,如果有帮助,示例中使用的“某处”域将始终相同。

更新:感谢蒂亚戈,他帮助我指明了正确的方向。

function check_URL() {

var url = "http://" + localStorage['t'] + ".somewhere.com";
var url1 = "http://" + localStorage['t1'] + ".somewhere.com";
var url2 = "http://" + localStorage['t2'] + ".somewhere.com";
var url3 = "http://" + localStorage['t3'] + ".somewhere.com";

var urlArray = ['url', 'url1', 'url2','url3'];
$(urlArray).each(function (urlItem) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
            "q=select%20*%20from%20html%20where%20url%3D%22"+
            encodeURIComponent(urlItem)+
            "%22&format=xml'&callback=?",
    function(data){
      if(data.results[0]){
        console.log("yes");
      } 
      else { 
      console.log("no");
      alert(url + " is not a valid URL or is down.");

     }
    }
  );
});
};

这似乎找到了任何未验证但警报已损坏的网址。

想法?

谢谢!

最后更新:下面发布的工作解决方案。

4

2 回答 2

2
var urlArray = ['url', 'url1', 'url2'];
$(urlArray).each(function (urlItem) {
    //do your stuff with your urlItem string
});

http://api.jquery.com/each/

于 2012-07-22T23:06:11.387 回答
0

这是我使用的解决方案。感谢@BaylorRae' 的指导!

function check_URL() {

  var url = "http://" + localStorage['t'] + ".somewhere.com";
  var url1 = "http://" + localStorage['t1'] + ".somewhere.com";
  var url2 = "http://" + localStorage['t2'] + ".somewhere.com";
  var url3 = "http://" + localStorage['t3'] + ".somewhere.com";

  var urlArray = [url, url1, url2, url3],
      invalidUrls = [];

  $.each(urlArray, function (i, urlItem) {
    $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
    "q=select%20*%20from%20html%20where%20url%3D%22"+
    encodeURIComponent(urlItem)+
    "%22&format=xml'&callback=?",
    function(data){
      if(data.results[0]){
        console.log("yes");
      } 
      else { 
        invalidUrls.push(urlItem);
      }
    }
    );
  });

  return invalidUrls;
};
于 2012-07-24T02:35:21.717 回答