使用jquery 1.10.2选中/取消选中所有复选框

关于这个主题有很多问题,但没有一个对我的问题有用,因为我不知道如何在我的代码中应用它们 – 我是jQuery的新手。

这是我的HTML页面:

现在我的jQuery看起来如下所示:

 $(function () { $("#one #positionable2 #xyz2 #tab1 #cbselectall").click(function () { if ($("#one #positionable2 #xyz2 #tab1 #cbselectall").is(':checked')) { $("#one #positionable2 #xyz2 #tab1 input[type=checkbox]").each(function () { //$(this).attr("checked", true); $(this).prop("checked", true); }); } else { $("#one #positionable2 #xyz2 #tab1 input[type=checkbox]").each(function () { //$(this).attr("checked", false); $(this).prop("checked", false); }); } }); }); 

请注意,我在表中有其他列,带复选框的列是第一列。 单击表标题中的复选框后,应选择数据行上的其他列,反之亦然。 不知何故,这是行不通的。

因为我是jQuery的新手,不知怎的,我无法让它工作。 请帮忙。

首先,您不需要在每个选择器中指定层次结构。

 $("#cbselectall").on('click', function() { $(this) .parents('table') // go to the table element .find(':checkbox') /* find all checkboxes (note you might need to specifiy if you have other checkboxes in the table that shouldn't get checked */ .prop('checked', $(this).is(':checked')); /* set the checked value to be the value of the check all checkbox */ })