开发者

Selecting the next instance within a class in jQuery

开发者 https://www.devze.com 2023-04-08 21:08 出处:网络
I have a table with alternating rows of course names and course descriptions. Here\'s some of the html (that I loop through):

I have a table with alternating rows of course names and course descriptions. Here's some of the html (that I loop through):

<tr>
    <td><a class="course_name_click" href='#'><%= course.name %></a></td>
</tr>

<tr class="course_descrip" height="200">
    <td style="word-开发者_如何学Pythonwrap: break-word" width="10"><%= course.descrip %></td>
</tr>

I'd like to make it so that when the user clicks on the course name, the course description slide toggles up and down. But I'm having trouble finding the right selector for the course descrip that appears right after the course name that is clicked. I've tried a bunch of different combinations of $(this) and .next(), but none seems to work. Here's my jquery so far:

  $('.course_name_click').click(function() {
    $('tr.course_descrip').slideToggle('slow');
    return false;
  });

As it appears above, clicking on any course name slide toggles every instance of tr.course_descrip. I only want it to slide toggle the instance that appears after the course name that is clicked.


$('.course_name_click').click(function() {
  $(this).closest('tr').next().slideToggle('slow');
  return false;
});


This is because $(this).next() gets the next sibling of the <a/> that was clicked, which is nothing. You will have to get it's parent's parent (the <tr/>) and do next on that:

$('.course_name_click').click(function() {
    $(this).parent().parent().next().slideToggle('slow');

    return false;
});

Here is a jsFiddle of it working.

Edit: Matt's answer may make more syntactic sense than doing .parent().parent()

0

精彩评论

暂无评论...
验证码 换一张
取 消