选择上一个元素 - jQuery

时间:2013-01-06 12:05:50

标签: jquery html checkbox

这是我的代码,

<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个与此类似的表行。我想要做的是,当我点击行中第3个td的span标签时,应选中位于同一行的复选框。

我试过这个,但它不起作用,

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

请帮我简短一下,

问候。

3 个答案:

答案 0 :(得分:2)

简单,使用.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/

答案 1 :(得分:1)

在您的代码中.parent()将选择父<td>个节点。要选择<tr>,您应该使用.parent().parent().closest("tr")

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

注意,最好应用.prop("checked", true).attr("checked", "checked")

答案 2 :(得分:1)

这可以通过

完成
$( '.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
} );
相关问题