简体   繁体   中英

Hide table row onclick using jQuery

I have a bunch of table rows such as:

<tr>
  <td>cell1</td>
  <td>cell2</td>
  <td><a href="action.php">cell3</a></td>
</tr>
<tr class="notes_row">
<td colspan="6">
<ul class="message warning no-margin" id="notes_box">
<li>Notes here</li>
</ul>
</td>
</tr>
<tr>
  <td>cell1</td>
  <td>cell2</td>
  <td><a href="action.php">cell3</a></td>
</tr>

The class="notes_row" is only there if notes are present for the row above it. How can I hide the tr and if its there the tr with the notes_row class below it without affecting the other rows using jquery? So if someone clicked cell3 the tr that link is in is hidden then if there is a notes table row below it, it hides that as well.

$('a[href=action.php]').click(function(){  // ... or however you attach to that link
    var row = $(this).closest('tr');

    // hide this row first
    row.hide();

    // next, get the next TR, see if it is a notes row, and hide it if it is
    var nxt = row.next();
    if (nxt.hasClass('notes_row'))
      nxt.hide();

    // stop link
    return false;
});

I think... Going by memory here.

EDIT

Couple minor fixes, and a fiddle link to see it in action:

http://www.jsfiddle.net/E6zcV/

This would be a good place for .delegate() , it can be as simple as:

$("#tableID").delegate("a[href='action.php']", "click", function(e) {
  $(this).closest("tr").hide().next("tr.notes_row").hide();
  e.preventDefault(); //don't follow the action.php href
});

You can test it out here . What this does is use .closest() to climb up to the <tr> , .hide() that row, select the .next() <tr> if it has the .notes_row class, and .hide() that as well. Finally I'm adding a event.preventDefault() on there so we don't actually navigate to action.php from the link itself.

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