结合循环

时间:2015-08-09 12:07:31

标签: jquery arrays loops

如何将这些循环组合在一起..

是否可以使循环使用第一个标记作为类别,然后访问将用于标题的下一个标记?

$(document).ready(function(){

//get root and current URL
var loc = document.URL;
var root = document.location.hostname;
var path = window.location.pathname;
var dir = path.substring(path.lastIndexOf('/'));

//read in posts from tumblr
if (root != 'www.tumblr.com') {
    var posts = tumblr_api_read.posts;
    for (var i in posts) {
        $('#project-list').append('<li><a href='+posts[i].url+'>'+posts[i].tags[0]+'</a></li>');
    }
} else {
    $('#project-list').append('<li><a href="#">project title</a></li>')
}

if (root != 'www.tumblr.com') {
var posts = tumblr_api_read.posts;
for (var i in posts) {
  $('#installation-list').append('<li><a href='+posts[i].url+'>'+posts[i].tags[1]+'</a></li>');
}
} else {
$('#installation-list').append('<li><a href="#">installation title</a></li>')
}

2 个答案:

答案 0 :(得分:0)

你可以像这样组合:

$(document).ready(function() {
    //get root and current URL
    var loc = document.URL;
    var root = document.location.hostname;
    var path = window.location.pathname;
    var dir = path.substring(path.lastIndexOf('/'));

    //read in posts from tumblr
    if (root != 'www.tumblr.com') {
        var posts = tumblr_api_read.posts;
        for (var i in posts) {
            $('#project-list').append('<li><a href=' + posts[i].url + '>' + posts[i].tags[0] + '</a></li>');

            $('#installation-list').append('<li><a href=' + posts[i].url + '>' + posts[i].tags[1] + '</a></li>');
        }
    } else {
        $('#project-list').append('<li><a href="#">project title</a></li>');

        $('#installation-list').append('<li><a href="#">installation title</a></li>');
    }
});

答案 1 :(得分:0)

你的意思是这样的

if (root != 'www.tumblr.com') {
    var posts = tumblr_api_read.posts;
    for (var i in posts) {
      $('#project-list').append('<li><a href=' + posts[i].url + '>' + 
                                  posts[i].tags[0] + '</a></li>');
      $('#installation-list').append('<li><a href=' + posts[i].url + '>' + 
                                  posts[i].tags[1] + '</a></li>');
    }
} else {
    $('#project-list').append('<li><a href="#">project title</a></li>')
    $('#installation-list').append('<li><a href="#">installation title</a></li>')
}