.change 函数的多个输入

Multiple inputs for .change function

我有一个 table,我想在其中每次触发一个复选框时删除一个 table 行。我让它在一行中工作(仅当我专门输入行的 ID 时)。有什么方法可以为 javascript 函数提供动态输入吗?我该怎么做?

HTML(嵌入ruby)

<tr class="showContainer <%= "hideTableRow#{comment.id}" %>">
  <th><%= check_box_tag "approved#{comment.id}", comment.id, comment.approved, data: { toggle: "hideTableRow#{comment.id}" }, class: 'comment-approve' %></th>
    <th><%= comment.username %></th>
    <th><%= comment.email %></th>
    <th><%= comment.body %></th>
</tr>

这转化为(两个条目)。

<tr class="showContainer hideTableRow1">
  <th><input type="checkbox" name="approved1" id="approved1" value="1" data-toggle="hideTableRow1"></th>
    <th>foobar username1</th>
    <th>foobar email1</th>
    <th>foobar body1</th>
</tr>

<tr class="showContainer hideTableRow3">
  <th><input type="checkbox" name="approved3" id="approved3" value="3" data-toggle="hideTableRow3"></th>
    <th>foobar username3</th>
    <th>foobar email3</th>
    <th>foobar body3</th>
</tr>

我的CSS:

.showContainer {
    display:block;
}

我的 JS:

$("#approved1").change(function () {
    $('.' + $(this).data('toggle')).toggle();
});

显然我的 JS 现在只适用于第一行 table。我该怎么做才能单独影响两者?

对不起,如果这是一个完全菜鸟的问题。接下来学习JS,哈哈

感谢您的帮助!

您想要 select 包含行,对吗?试试这个:

$('.approved-checkbox').change(function(e){
    $(e.target).closest('.showContainer').toggle();
});

然后为复选框指定 'approved-checkbox' 的 class 或您要使用的任何名称。

.closest() documentation