jQuery查找子复选框
我有一个简单的jQuery问题: 我有以下类型的表:jQuery查找子复选框,jquery,checkbox,html-table,Jquery,Checkbox,Html Table,我有一个简单的jQuery问题: 我有以下类型的表: <table id="my_table"> <tr> <td><input type="checkbox" value="24"></td> <td> Click Here To Check The Box </td> <td> Or Click Here </td> </tr> </tab
<table id="my_table">
<tr>
<td><input type="checkbox" value="24"></td>
<td> Click Here To Check The Box </td>
<td> Or Click Here </td>
</tr>
</table>
但上述方法不起作用。在单击的行上选择复选框有什么快速的想法吗?谢谢 jQuery方法查找最近的父级
如果确实要搜索子元素,可以尝试以下操作:
$("#my_table tr").click(function(e) {
$(":checkbox:eq(0)", this).attr("checked", "checked");
});
基本上,您是在搜索表行中找到的第一个复选框
一些参考资料
……编辑:底部的最佳解决方案 假设只有一个复选框,我会将事件附加到
td
而不是tr
:
$('#my_table td').click(function(e){
$(this).parent().find('input:checkbox:first').attr('checked', 'checked');
});
如果您还想取消选中复选框
$('#my_table td').click(function(e) {
var $tc = $(this).parent().find('input:checkbox:first'),
tv = $tc.attr('checked');
$tc.attr('checked', !tv);
});
此函数还需要应用于复选框以否定默认行为
编辑:如果目标是输入,最合理的解决方案是取消功能:
也试试这个
$("#my_table tr").click(function(e) {
$(this).closest("type:checkbox").attr("checked", checked");
});
我制作了一个简单的脚本来选中特定tr中的第一个复选框。
关于切换,我只想在发布这个答案之前尝试一下。这是错误的,因为jQuery closest()方法会处理DOM树。这意味着它将找到最接近的匹配父项。谢谢mVChr。很好的例子链接,我也喜欢取消选中的功能。干杯事实上,我有一个最新的问题。我注意到在这个例子中,你甚至不能点击“复选框”本身。有没有办法解决这个问题?再看一次例子2。我搞定了。好吧,抱歉让事情复杂化了。我感谢你的帮助。请检查:我正在加载的表是通过Ajax加载的,所以我需要使用jQueryLive方法。但是,我修改的函数似乎不起作用。单击复选框仍然不起作用。但是,请单击“确实有效”。@clockw0rk而不是
:first
,您可以使用:eq(4)
或其他任何工具。请参阅jQueryAPI文档。
var cbcfn = function(e) {
if (e.target.tagName.toUpperCase() != "INPUT") {
var $tc = $(this).parent().find('input:checkbox:first'),
tv = $tc.attr('checked');
$tc.attr('checked', !tv);
}
};
$('#my_table td').live('click', cbcfn);
$("#my_table tr").click(function(e) {
$(this).closest("type:checkbox").attr("checked", checked");
});
$("#my_table tr").click(function(e) {
state= $(this).find(":checkbox:eq(0)").attr("checked");
if (state==true){ // WITH TOGGLE
$(this).find(":checkbox:eq(0)").removeAttr("checked");
}else {
$(this).find(":checkbox:eq(0)").attr("checked", "checked");
}
});