0

是否可以使用 jQuery 将数组中每个 URL 的内容附加到 URls 列表中的给定容器?

像这样:

<li class="contacts"><a href="index.php#contact1">Contact 1</a>
<li class="contacts"><a href="index.php#contact2">Contact 2</a>
<li class="contacts"><a href="index.php#contact3">Contact 3</a>
<li class="contacts"><a href="index.php#contact4">Contact 4</a>

我知道如何使用 jQuery 获取 URL 数组:

$(document).ready(function() {
    var allLinks = $('li.contacts a').map(function(i,el) { return $(el).attr('href');     });
    console.log($(allLinks));
});

好的,我在 allLinks 变量中有一个 URL 数组。我现在想用 .get() 函数附加每个 URL 的 #content 元素的内容。

如何从数组中的第一个 URL 循环到最后一个 URL 并将其内容附加到我的当前页面?它基本上应该像这样结束:

<div id="currentpage">
//#content of URL1
//#content of URL2
//#content of URL3
//#content of URL4
</div>

URL 列表是动态生成的(这不是问题)。

我试过这个:

$(document).ready(function() {
    var allLinks = $('li.contacts a').map(function(i,el) { return $(el).attr('href'); });
    console.log($(allLinks));

  var curr  = 0;
        if (curr++ > allLinks.length) curr = 0;

        $.get(allLinks[curr],function(data){
        var myContent = $(data).find('#content').children();
            jQuery('#wrapper').append(myContent);
   });
});

但没有成功。有什么线索吗?

4

1 回答 1

0

更新答案:(将点击的 href 加载到 div 中)

$('.contacts a').click(function() {
  var url= $(this).attr('href');
  $('#currentpage').html('loading...');
  $.ajax({
     url: url
  }).success(function(data) {
     $('#currentpage').html(data);
  });       
  return false;
});
//JSBin http://jsbin.com/ucobuv/3/edit
//No need for the allLinks variable here

旧答案:(加载所有链接)

(function getContent(i) {
    $.ajax({
        url: allLinks[i++]
    }).success(function(data) {
        $('#currentpage').append(data);
        if(allLinks[i]) getContent(i);
    });
})(0);
//JSBin http://jsbin.com/ucobuv/1/edit
于 2013-02-05T13:01:19.280 回答