如何在 table 的单个行上捕获 DOM

How to catch DOM on individual row of a table

我有一个 table,它的每一行都包含一个复选框和多个输入框。 当我选中复选框时,我想更改该行所有输入框的值。目前我只访问第一个输入框。 我的代码是。

<table>
    <tr>
        <td><input type="checkbox" class='isActive'/></td>
        <td><input type="text" class='name'/></td>
        <td><input type="text" class='name'/></td>
        <td><input type="text" class='name'/></td>
    </tr>
    <tr>
        <td><input type="checkbox" class='isActive'/></td>
        <td><input type="text" class='name'/></td>
        <td><input type="text" class='name'/></td>
        <td><input type="text" class='name'/></td>
    </tr>
</table>

和 JS

$('body').on('click','.isActive',function(){
    if ($(this).is(':checked')) {
        $(this).parent().next().find('.name').val('Demian');
    }
});

如何解决这个问题。 JS fiddle link 是 http://jsfiddle.net/Iftakharul_alam/txpg8mhf/1/

这样做:

$('body').on('click','.isActive',function(){
  if($(this).is(':checked')) {
    $(this).closest('tr').find('.name').val('Demian');
  } else {
    $(this).closest('tr').find('.name').val('');
  }
});

这将更改当前行中的所有 .name 个元素。


正如 j08691 指出的那样,您可以使用三元运算符来减少代码。

将多个 jQuery 方法链接在一起时,您可以将它们分开以便于阅读:

$('body').on('click','.isActive',function(){
  $(this)
    .closest('tr')
    .find('.name')
    .val(this.checked ? 'Demian' : '');
});

请注意,您可以将 checked 属性 简称为 this.checked 而不是 $(this).is(':checked')

Fiddle

你只需要使用 .nextAll() 而不是 .next():

$('body').on('click', '.isActive', function () {
    $(this).parent().nextAll().find('.name').val($(this).is(':checked') ? 'Demian' : '');
});

jsFiddle example

而且如您所见,您可以使用ternary operator来减少代码量。

而不是 next() 使用 parent()

$('body').on('click','.isActive',function(){
    if ($(this).is(':checked')) {
        $(this).parent().parent().find('.name').val('Demian');
    }
});