开发者

Jquery/javascript onclick display next row

I have a table that has a row that is hidden using display:none. I want to show the row when a button is clicked. How can I do this??

<table>

<tr>
<td>
<button cl开发者_Python百科ass="shownextrow">Show Next Row</button>
</td>
</tr>

<tr style="display:none">
<input type="text" name="input"/>
</tr>

</table>


You can bind to the button and find it relatively, like this:

$("button.shownextrow").click(function() { 
  $(this).closest("tr").next().show();
});

This goes from the button ($(this)) up to the <tr> using .closest() then gets the .next() sibling <tr> to .show(). You may want to use .toggle() instead of .show() but the rest is the same.

You can give it a try here. Note that you have a <input> directly in a <tr> in the example, I wrapped this in a <td> to make it a valid demo.


Nick's approach is fine, but I'd probably use a single handler for the entire table ("event delegation") via the delegate function, rather than individual handlers on each button, like this:

$('#theTable').delegate("button.shownextrow", "click", function() {
    $(this).closest("tr").next("tr").show();
});

Live example

Amongst other things, that lets you add more pairs of rows to the table (and remove pairs of rows) without worrying about hooking up / unhooking event handlers for them. Mind, it does require that nothing directly in the hierarchy between the button element and the table element eats clicks...


Here's my older example that didn't use delegate, just for historical purposes — wow does delegate simplify the code:

$('#theTable').click(function(event) {
    var button = $(event.target).closest("button.shownextrow");
    if (button.length > 0) {
        button.closest("tr").next("tr").show();
    }
});

Live example


You can simply call the parent tr to show the next tr:

$('button.shownextrow').click(function () {
    $(this).parents('tr').next('tr').show();
});

I used it and it worked just fine.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜