【问题标题】:Selecting next element of the parent选择父元素的下一个元素
【发布时间】:2013-01-07 11:04:40
【问题描述】:

这是我的编码,

<tr class="ar">
   <td>
        <input type="checkbox" class="cbx">
   </td>    
   <td>
        <span class="spc">book</span>
   </td> 
</tr>
<tr class="ar"></tr>

我想要做什么,如果单击复选框或范围(在第一个 tr 内),我想将一个类切换到第二个 tr。此外,如果复选框已经被选中,那么我需要在单击其中任何一个时取消选中。

【问题讨论】:

  • 到目前为止你得到了什么?
  • 那里有多少个?是否需要复选框的单选按钮功能。

标签: jquery html checkbox next


【解决方案1】:
$('td input[type=checkbox], td span').click(function(){
    $(this).closest('tr')
        .find('input[type=checkbox]')
        .prop("checked", false)
        .end()
        .next()
        .toggleClass('yourclass');
});

【讨论】:

  • 这将得到下一个td 而不是tr。
  • @AleksandrM 谢谢,已修复。
【解决方案2】:

试试这个

$(".cbx2").click(function(){
  $(this).closest("tr.ar").next().toggleClass("toggled_class");
});

$(this).closest("tr.ar") 将为您提供该对象的最接近的父 tr 元素与 ar 类,.next 将获得该类型的下一个元素,即您的第二个 tr。

【讨论】:

  • 你需要closest()而不是parents(),没有必要一路向上移动DOM并可能遇到另一个具有ar类的元素
  • @TimJoyce:是的,最接近的可能更好。
【解决方案3】:

试试这个......如果你想取消选中复选框......

$('#your_checkbox_id').live('click' , function() {
    if($('#your_checkbox_id').is(':checked')) {
        $('#your_checkbox_id').removeAttr('checked');
        $(this).next().toggleClass('class_name');
    }
});

【讨论】:

  • 你不需要重复使用同一个选择器。只需使用this。此外,live 已被弃用。
【解决方案4】:
$('.cbx, .spc').click(function(e){
    $('.cbx').prop('checked', false); // uncheck everything

    $(this).toggleProp(checked, $(this).prop('checked')) // check/uncheck current
           .closest('.ar').toggleClass('yourClass'); // toggle class on next tr
});

【讨论】:

    【解决方案5】:

    试试这个:http://jsfiddle.net/kPJJf/

    $('td input[type=checkbox], td span').click(function () {
           $(this).parents('tr').next('tr').find('span').toggleClass('spc');
       if($(this).parents('tr').next('tr').find('input[type="checkbox"]').is(':checked')==false){
          $(this).parents('tr').next('tr').find('input[type="checkbox"]').prop('checked', true);
       }else{
          $(this).parents('tr').next('tr').find('input[type="checkbox"]').removeAttr('checked');
       }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      相关资源
      最近更新 更多