如何在此代码上使用.each进行迭代?

时间:2012-07-22 22:57:14

标签: jquery

还在学习并需要一些帮助。

此代码示例检查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.");

     }
    }
  );
});
};

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

想法?

谢谢!

最终更新:工作解决方案发布在下方。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分: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;
};