javascript Jquery 单击检查最近的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20500682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery click check nearest checkbox
提问by David Brooks
I'm trying to use a link to check a checkbox with jQuery. My HTML is:
我正在尝试使用链接来检查带有 jQuery 的复选框。我的 HTML 是:
<table>
<tr>
<td><input type="checkbox" value="test" /></td>
<td><a class="editbutton" href="#">edit</a></td>
</tr>
</table>
I have been playing with this jquery:
我一直在玩这个 jquery:
jQuery('.editbutton').click(function($) {
jQuery(this).closest('[type=checkbox]').attr('checked', true);
});
Unfortunately this isn't working. Any ideas?
不幸的是,这不起作用。有任何想法吗?
回答by Rajaprabhu Aravindasamy
Use .prop()
instead of .attr()
, Because .prop
is made for setting the properties
. By the way your selector is wrong. .closest()
will traverse up the dom tree.
使用.prop()
代替.attr()
, 因为.prop
用于设置properties
. 顺便说一下,您的选择器是错误的。.closest()
将遍历 dom 树。
Please read the following for more reference : .prop().closest()
请阅读以下内容以获取更多参考: .prop() .closest()
Try this,
试试这个,
jQuery('.editbutton').click(function($) {
jQuery(this).closest('td').prev().find('[type=checkbox]').prop('checked', true);
});
Or as @kappa suggested.
或者像@kappa 建议的那样。
jQuery('.editbutton').click(function($) {
jQuery(this).closest('tr').find('[type=checkbox]').prop('checked', true);
});