简体   繁体   中英

DOM Traversal with jQuery

With this markup

<div class="col-md-3">
  <div id="carousel-race-track">
    <%= image_tag 'race_track/track_curved.jpg', data: { engine: 'Sports'}  %>
    <%= image_tag 'race_track/track_hills.jpg', data: { engine: 'Hills'}  %>
    <%= image_tag 'race_track/track_rough.jpg', data: { engine: 'Rough'}  %>
    <%= image_tag 'race_track/track_straight.jpg', data: { engine: 'Straight'}  %>
  </div>
  <p class="lead"><a class="btn btn-lg btn-info select">Select</a></p>
</div>

When I click on the .select for example, how would I traverse the DOM to get to the div #carousel-race-track ?

I'm going to have multiple carousels so will wildcard the id search, prefixed with carousel- .

I'm trying to say something like this:

$('.select').on('click', function(e){
  e.preventDefault();
  var carousel = $(this).closest("[id^='carousel-']");
  $(carousel).cycle('pause');
});

Is closest the wrong method here ?

Closest finds the closest parent that matches the selector. You want to use parent to get to .lead and then prev which finds the previous sibling that matches the selector.

$('.select').on('click', function(e){
  e.preventDefault();
  var carousel = $(this).parent().prev("[id^='carousel-']");
  $(carousel).cycle('pause');
});

Or you could do this:

var carousel = $(this).closest('.col-md-3').find("[id^='carousel-']");

This finds closest .col-md-3 parent then finds the carousel inside it.

$(this).parent().siblings(); should do the job.

If you have different siblings you have to specify the one you're interested on with a selector.

Keep in mind that returns a jQuery object, so you have directly append any jQuery method to it:

carousel.cycle('pause');

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