Domanda

Example of my code:

<section id="reports">

  <div class="report">
    <div class="report-expand">MORE</div> <!-- this one is clicked -->
  </div>
  <ul class="report-moreinfo"></ul> <!-- I want to select this one -->

  <div class="report">
    <div class="report-expand">MORE</div>
  </div>
  <ul class="report-moreinfo"></ul>
  <div class="report">
    <div class="report-expand">MORE</div>
  </div>
  <ul class="report-moreinfo"></ul>

</section>

This is part of my jQuery:

$('.report').on('click', '.report-expand', function(e) {
  // $(this) === '.report-expand'
  $(this).closest('.report') // now what..?
}

How do I finish the traversing to properly select the ul.report-moreinfo that follows the .report I currently have selected?

È stato utile?

Soluzione

$(this).closest('.report').next();

since the list is the next sibling. If you want to get the previous sibling, you would use .prev.
More info: http://api.jquery.com/next/, http://api.jquery.com/prev/.

Here is a list of all traversal methods.

Since you bound the event handler to the .report element anyway, you can also make use of event.delegateTarget instead of $(this).closest(...):

$(event.delegateTarget).next();

Altri suggerimenti

You can use this

  $(this).parent().next()

$(this).parent() will give report div

You can use .next([selector]) function. Something like this:

$(this).closest('.report').next('ul.report-moreinfo');

But since div.report is the parent of div.report-expand you can just do:

$(this).parent().next('ul.report-moreinfo');

or use the delegateTarget provided by the click event callback:

$(e.delegateTarget).next('ul.report-moreinfo');

You can use:

$(this).parent().next();

Using .parent() is preferable to using .closest() for performance reasons as long as .report-expand is always the direct child of .report.

Edit: Having reviewed other answers, I think $(event.delegateTarget).next();, which Felix Kling first suggested, is the most efficient query.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top