iterate values in $.each nested Jquery

Asked

Viewed 686 times

5

I’m getting a full table from my server side, looking for td with information I want and save that tr integer in a variable as below:

var rowVoo;

$(table).find("tr td").each(function () {
      if ($.trim($(this).text()) == "Porto Velho - RO") {
           rowVoo = $(this).closest("tr");
      }
});

The variable rowVoo stays as it is below:

<tr>
    <td>Porto Velho - RO</td>
    <td>11</td>
    <td>1 ( 9.1 %)</td>
    <td>0 ( 0 %)</td>
    <td>0 ( 0 %)</td>
</tr>

I have a list as abixus:

<ul class="list-voos">
      <li><span></span> VOOS PREVISTOS</li>
      <li><span></span> ATRASADOS AGORA</li>
      <li><span></span> VOOS CANCELADOS</li>
      <li><span></span> ATRASADOS NO DIA</li>
</ul>

I need to pass on the values that are within the td for the span who are on the list.

I’m looking for span that are within the list:

var list = $(".list-voos").find("li").find("span");

And I try to iterate the values:

$(rowVoo).find("td").each(function () {
     var that = $(this);
     $(list).each(function () {
         console.log($(this).text(that.text()));
         return null;
     });
});

But the values are doubled and the span of the list always get the last value of the td

2 answers

5


You have to use the index that the function .each() pass/make available.

Forehead like this:

var lis = $('ul.list-voos li');
$(rowVoo).find("td").each(function (i) {
     $(lis).find('span').eq(i).html(this.innerHTML);
});

Function (index, value){

The each method allows a function that gives you two variables. The first is the element’s Dice in the collection, the second is the collection’s own element. In the case of jQuery, it is the same value as the this within that function.

Example: http://jsfiddle.net/CrXD4/2/

  • 1

    Thank you, it worked perfectly!

2

improved performance[updated]:

var i, e, tableTeste = $("table").find("tr td"),
  ulLi = $(".list-voos").find("li span");

for (var i = 0, e = tableTeste.length; i < e; i++) {
  var tdValue = tableTeste[i].innerHTML;

  ulLi.eq(i).html(tdValue);


}

before:

var i, e, tableTeste = $("table").find("tr td"),
  ulLi = $(".list-voos").find("li span");

for (var i = 0, e = tableTeste.length; i < e; i++) {
  var tdValue = tableTeste.eq(i).html();
  ulLi.eq(i).html(tdValue);

}

see comparison using each(), for(){} and for(){} with innerHTML: http://jsperf.com/test-each-for-each/2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.