简体   繁体   中英

Show/Hide button for each row in table

I have two buttons in each row of a table. You see button 1 at first. When button 1 is clicked, it disappears and button 2 pops up. This is simple, but I don't understand how to create this behavior for each row individually. Right now it only works for the first row.

I have created a codepen to better illustrate this:

http://codepen.io/cavanflynn/pen/qdVorB

I only understand how to do this using their id's so it only works for the first row.

var first = document.getElementById( 'first' ),
second = document.getElementById( 'second' );

How would you get this behavior to work for each row on its own? Thanks!

Because id must be unique values document.getElementById() will get the first one;I think you can change the id to class and add an param(witch row) to toggle function. Or in toggle function using js to get the Sbiling node

As you said you have jQuery, things get really simple. Just replace your IDs with classes and, for each button clicked, get the second within the scope of its parent (ie the row). Here's the updated codepen .

$('.first').click(function() {
  $(this).hide();
  // Using .css() instead of .show() because .show() would render the button with its default display (inline) instead of block.
  $(this).parent().find('.second').css('display', 'block');
});

Like @casimiryang said, problem are the ids. You can only have 1 element with the same ID on the page.

So to solve the problem you can use classes instead and add click event handlers with jQuery.

$(".first").on("click", function(){
  $(this).hide();
  $(this).next().show();
});

$(".second").on("click", function(){
  $(this).hide();
  $(this).prev().show();
});

Here is the codepen: solution

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