简体   繁体   中英

jQuery DOM traversal in each function

I'm trying to do a simple DOM transverse in an each loop. The issue is that jquery is selecting multiple instances of the specified class instead of the one I'm trying to select using $(this). This is my markup:

@foreach ($details as $i)
  <tr>
    <div class="ajax-tracking-check">
      <input type="hidden" name="trans_id" value="{{ $i->transaction_id }}"/>
      <input type="hidden" name="tracking" value="{{ $i->tracking_number }}"/>
      <input type="hidden" name="carrier" value="{{ $i->shipping_carrier }}"/>
    </div>
    <td class="td-image">{{ HTML::image($i->image_url, 'item-image', array('class' => 'sir')) }}</td>
    <td>{{ $i->item }}</td>
    <td>${{ $i->price }}</td>
    <td>{{ date('M d, Y',strtotime(Transaction::where('transaction_id', $i->transaction_id)->pluck('created_at'))) }}</td>
    <td class="breh">
      {{ $i->tracking_number }}
      <!-- </br> -->
      {{ $i->shipping_carrier }}
    </td>
    <td class="status"><h2>{{ $i->status }}</h2></td>
  </tr>
@endforeach

I'm trying to select the class ".breh" with this line in my js:

var field    = $(this).parent().find('td.breh');

This is the entire function:

   $('.ajax-tracking-check').each(function() {

      var number   = $(this).find('input[name="tracking"]').val();
      var trans_id = $(this).find('input[name="trans_id"]').val();
      var carrier  = $(this).find('input[name="carrier"]').val();
      var field    = $(this).parent().find('td.breh');

      $.post(
        'purchased/ajax/tracking/check',
        {
          trans_id: trans_id,
          number:   number,
          carrier:  carrier
        },
        function(data) {
          if (number !== "1")
          {
            // field.text(data['city']+', '+data['state']);
            field.addClass('red');
          }
        }
      );
  });

The first instance table row's var number is equal to 1 BUT the second row is equal to a random string. With my if statement, I'm trying to add the class "red" but it's added to both instances of "field".

The HTML is not valid.

Your ".ajax-tracking-check" DIV is not contained by a TD inside the table and because of that on the statement

var field = $(this).parent().find('td.breh');

The parent() is returning the BODY element and after that the find() returns all of the .breh element ocurrences.

You should wrap that DIV on a TD element (you can hide it with a display:none) and then the statement would be

var field = $(this).parents('tr').find('td.breh');

Note the plural of "parents()", this will go up in the parents chain until it finds the element TR not just one level as with the singular "parent()"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM