Jquery点击查看最近的复选框

Dav*_*oks 3 javascript jquery click

我正在尝试使用链接来检查jQuery的复选框.我的HTML是:

<table>
  <tr>
    <td><input type="checkbox" value="test" /></td>
    <td><a class="editbutton" href="#">edit</a></td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

我一直在玩这个jquery:

jQuery('.editbutton').click(function($) {
    jQuery(this).closest('[type=checkbox]').attr('checked', true);
});
Run Code Online (Sandbox Code Playgroud)

不幸的是,这不起作用.有任何想法吗?

Raj*_*amy 10

使用.prop()而不是.attr(),因为.prop是为了设置properties.顺便说一下你的选择器是错误的..closest()将遍历dom树.

请阅读以下内容以获取更多参考: .prop(). closest()

试试这个,

jQuery('.editbutton').click(function($) {
    jQuery(this).closest('td').prev().find('[type=checkbox]').prop('checked', true);
});
Run Code Online (Sandbox Code Playgroud)

或者像@kappa建议的那样.

jQuery('.editbutton').click(function($) {
    jQuery(this).closest('tr').find('[type=checkbox]').prop('checked', true);
});
Run Code Online (Sandbox Code Playgroud)

DEMO