简体   繁体   English

显示/隐藏表中每一行的按钮

[英]Show/Hide button for each row in table

I have two buttons in each row of a table. 表格的每一行都有两个按钮。 You see button 1 at first. 您首先会看到按钮1。 When button 1 is clicked, it disappears and button 2 pops up. 单击按钮1时,它消失并且按钮2弹出。 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 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. 我只了解如何使用其ID来执行此操作,因此它仅适用于第一行。

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. 因为id必须是唯一的值document.getElementById()将获得第一个;我认为您可以将id更改为class并添加param(witch row)以切换功能。 Or in toggle function using js to get the Sbiling node 或者在使用js的切换功能中获取Sbiling节点

As you said you have jQuery, things get really simple. 正如您说的那样,有了jQuery,事情就变得非常简单。 Just replace your IDs with classes and, for each button clicked, get the second within the scope of its parent (ie the row). 只需将您的ID替换为类,对于每个单击的按钮,将第二个添加到其父级(即该行)的范围内。 Here's the updated codepen . 这是更新的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. 就像@casimiryang所说,问题是id。 You can only have 1 element with the same ID on the page. 您在页面上只能有1个具有相同ID的元素。

So to solve the problem you can use classes instead and add click event handlers with jQuery. 因此,要解决该问题,您可以改用类,并在jQuery中添加click事件处理程序。

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

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

Here is the codepen: solution 这是codepen: 解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM