【问题标题】:How to select the next table's row clicking a checkbox [closed]如何单击复选框选择下一个表的行[关闭]
【发布时间】:2012-02-08 23:00:58
【问题描述】:

这里是 HTML:

<tr>
    <td>
        Customer Reviews
    </td>
    <td>
        <input type="checkbox" name="p_reviews" /> (checkbox that trigger action)
    </td>
</tr>
<tr> (row to select)
    <td>
        How many reviews do you want to display?
    </td>
    <td>
    ...
    </td>
</tr>

这里是javascript:

$("form[name='myform'] input[name='p_reviews']").click(function() {
if ($(this).is(':checked')){
    $(this).closest('tr').next().show();
} else{
    $(this).closest('tr').next().hide();
}
});

这不起作用。有什么建议吗?

编辑:对不起,伙计们,是的,它正在工作。只是缺少一个 HTML 双引号!

【问题讨论】:

  • 它似乎工作正常:jsfiddle.net/RoryMcCrossan/AKc7D
  • 假设您的选择器是正确的,并且在执行此代码时 DOM 已准备就绪,那么您所拥有的应该可以工作:jsfiddle.net/XGPt9/4
  • 对不起,伙计们,是的,它正在工作。只是缺少一个 HTML 双引号!谢谢大家...
  • 您应该考虑使用 CSS 类甚至 ID,以便更轻松地选择元素。
  • @stefan 这个想法正好相反。不要使用太多的 ID 或类。我是坏人吗? 8)

标签: jquery html-table css-selectors row


【解决方案1】:
$('form[name="myform"] input[name="p_reviews"]').click(function() {
    if ($(this).is(':checked')){
        $(this).closest('tr').next('tr').show();
    } else{
        $(this).closest('tr').next('tr').hide();
    }
});

【讨论】:

  • $(this).closest('tr').next('tr').toggle(this.checked); 可能是什么? :)
【解决方案2】:

确保在准备好的文档上运行该代码。你也可以使用this.checked。试试这个

$(function(){
  $("form[name='myform'] input[name='p_reviews']").click(function() {
     if (this.checked){
         $(this).closest('tr').next().show();
     } else{
         $(this).closest('tr').next().hide();
     }
  });
});

您也可以使用更简单的切换。

    $(function(){
      $("form[name='myform'] input[name='p_reviews']").click(function() {
         $(this).closest('tr').next().toggle(this.checked);
      });
    });

【讨论】:

  • 他也可以使用toggle()
  • @Stefan - 检查我编辑的答案。
  • @stefan 是的,toggle() 在这里很有用(我在内部块中有更多代码)。
  • @NomikOS - 如果在许多地方使用此逻辑,切换将减少您的代码。
猜你喜欢
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 2018-09-01
  • 1970-01-01
相关资源
最近更新 更多