迭代ajax响应div并使用jquery将子元素添加到数组中

时间:2017-03-25 14:56:08

标签: javascript jquery iteration

我有一个html文档,其中有许多具有相同类的div,如何迭代每个div并将其元素的文本添加到多维数组?

HTML:

int

结果应该是这样的

<div class="testimonial" data-index="1">
    Testimonial 1
    <a href="" class="member-item-link">the link1</a>
    <span class="old-rank">50</span>
    <span class="new-rank">30</span>
</div>
<div class="testimonial" data-index="2">
    Testimonial 2
    <a href="" class="member-item-link">the link2</a>
    <span class="old-rank">50</span>
    <span class="new-rank">30</span>
</div>
<div class="testimonial" data-index="3">
    Testimonial 3
    <a href="" class="member-item-link">the link3</a>
    <span class="old-rank">50</span>
    <span class="new-rank">30</span>
</div>
<div class="testimonial" data-index="4">
    Testimonial 4
    <a href="" class="member-item-link">the link4</a>
    <span class="old-rank">50</span>
    <span class="new-rank">30</span>
</div>
<div class="testimonial" data-index="5">
    Testimonial 5
    <a href="" class="member-item-link">the link5</a>
    <span class="old-rank">50</span>
    <span class="new-rank">30</span>
</div>

我尝试了类似的东西,但它没有用(BTW我通过ajax调用获取文档)

testimonials = [["the link1",50,30],["the link2",50,30]["the link3",50,30],...,];

1 个答案:

答案 0 :(得分:0)

您的代码是正确的,但有几个问题。首先,.testimonial元素位于返回的HTML的根级别,因此您需要使用filter()来检索它们,因为在您最初拥有的上下文选择器中没有要查找的父元素

其次,您需要遍历DOM以查找当前推荐内的相关元素。您当前的代码将全部选中它们。

最后,您定义的变量名称与您在数组中放置的变量名称不匹配。另请注意,您可以使用map()代替each()循环来简化代码。试试这个:

// in this example 'data' is the response from your AJAX request
var data = '<div class="testimonial" data-index="1">Testimonial 1<a href="" class="member-item-link">the link1</a><span class="old-rank">50</span><span class="new-rank">30</span></div><div class="testimonial" data-index="2">Testimonial 2<a href="" class="member-item-link">the link2</a><span class="old-rank">50</span><span class="new-rank">30</span></div><div class="testimonial" data-index="3">Testimonial 3<a href="" class="member-item-link">the link3</a><span class="old-rank">50</span><span class="new-rank">30</span></div><div class="testimonial" data-index="4">Testimonial 4<a href="" class="member-item-link">the link4</a><span class="old-rank">50</span><span class="new-rank">30</span></div><div class="testimonial" data-index="5">Testimonial 5<a href="" class="member-item-link">the link5</a><span class="old-rank">50</span><span class="new-rank">30</span></div>';

var testimonials = $(data).filter('.testimonial').map(function() {
  var the_link = $(this).find("a.member-item-link").text();
  var the_oldrank = $(this).find(".old-rank").text();
  var the_newrank = $(this).find(".new-rank").text();

  return [[the_link, the_oldrank, the_newrank]];
}).get();

console.log(testimonials);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>