【问题标题】:Selecting previous element - jQuery选择上一个元素 - jQuery
【发布时间】:2013-01-06 12:05:50
【问题描述】:

这是我的代码,

<tr>
    <td>
        <input type="checkbox" class="cbx" name="cbx">
    </td>
    <td>
        <div>some content</div>
    </td>
    <td>
        <span class="book">Book now</span>
    </td>
</tr>

我的页面中有大约 20 个与此类似的表格行。我想要做的是,当我单击该行中第三个 td 中的 span 标签时,应选中同一行中的复选框。

我试过了,但它不起作用,

$('.book').click(function() {
   $(this).parent().find('.cbx').attr('checked',true);
});

请帮我缩短这个,

问候。

【问题讨论】:

  • $(this).parent() 只会查看 &lt;td&gt; 的内部。要么.parent() 两次,要么做一个更优雅的解决方案,比如 roXon's。

标签: jquery html checkbox


【解决方案1】:

简单,使用.closest() 方法找到tr 而不是去搜索你的.cbx ! :)

$('.book').click(function() {
   $(this).closest('tr').find('.cbx').prop('checked',true);
});

您的示例指向您的 TD 元素,因为您只使用了 .parent()
要到达TR 而不是使用.parent().parent(),只需使用.closest('tr')

http://api.jquery.com/closest/
http://api.jquery.com/prop/

【讨论】:

  • 非常感谢罗克森。它的工作就像一个魅力。抱歉,由于我的状态,我不能投票给你。
  • @user1915190 你不能投票,但你可以接受答案!点击投票箭头附近的'V'复选标记
  • @user1915190 THX :) 您确实投票了,但您没有接受正确的答案。 :|
  • 它说再等5分钟
  • @user1915190 当然,这可以让您在决定谁为(最快或)最有用的答案点赞之前查看更多答案
【解决方案2】:

在您的代码中.parent() 将选择父节点&lt;td&gt;。为了选择&lt;tr&gt;,您应该使用.parent().parent().closest("tr")

$(".book").on("click", function() {
    $(this).closest("tr").find(".cbx").prop("checked", true);
});

注意,最好申请.prop("checked", true).attr("checked", "checked")

【讨论】:

    【解决方案3】:

    这很简单

    $( '.book' ).on( 'click', function() {
        var $tr = $( this ).parents( 'tr' ).eq( 0 );
        // get the parenting tr
    
        $( '.cbx', $tr ).attr( 'checked', true );
        // select elements matching '.cbx' inside of $tr and check them
    } );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-16
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 1970-01-01
      • 2021-10-03
      相关资源
      最近更新 更多