<input type=checkbox id=selectall>
<!– The next step is giving each of the rows their own checkbox.
we put each row’s checkbox into the ‘selectable’ class, since there can be many rows,
and we want each of the rows’ checkboxes to have the same behavior. –>
<input type=checkbox class=selectable>
<!– The final step is bringing it all together with some jQuery code. –>
// remember that all jQuery setup code must be in this document.ready() function,
// or contained within its own function in order to function correctly.
$(document).ready(function(){
// We use the jQuery selection syntax to find the selectall checkbox on the page
// (note the ‘#’ which signifies ID), and we tell jQuery to call the selectAll()
// function every time someone clicks on the checkbox (we’ll get to Events in a
// future article).
$(“#selectall”).click(selectAll);
});
// This function will get called every time someone clicks on the selectall checkbox
function selectAll()
{
// this line determines if the selectall checkbox is checked or not. The attr()
// function, discussed in a future article, simply returns an attribute on the
// given object. In this case, it returns a boolean if true, or an undefined if
// it’s not checked.
var checked = $(“#selectall”).attr(“checked”);
// Now we use the jQuery selection syntax to find all the checkboxes on the page
// with the selectable class added to them (each row’s checkbox). We get an array
// of results back from this selection, and we can iterate through them using the
// each() function, letting us work with each result one at a time. Inside the
// each() function, we can use the $(this) variable to reference each individual
// result. Thus, inside each loop, it finds the value of each checkbox and matches
// it to the selectall checkbox.
$(“.selectable”).each(function(){
var subChecked = $(this).attr(“checked”);
if (subChecked != checked)
$(this).click();
});
}
结束语
jQuery 是 Web 应用程序开发社区中非常受欢迎的 JavaScript 库,并且随着富 Internet 应用程序越来越普及,它将变得更加重要。由于许多公司都在线迁移内部应用程序,并且在线移动日常的桌面应用程序(包括文字处理器和电子表格),能够简化开发并实现跨平台支持的 JavaScript 库将成为设计应用程序架构的必选技术。
这份关于 jQuery 的系列文章的第一篇介绍了 jQuery 语法,如何在您自己的 JavaScript 代码中正确使用 jQuery,以及如何在结合使用其他库时避免冲突。此外,本文还介绍了 jQuery 搜索和选择语法,它们是其他 jQuery 功能的基础。它使您可以简单快捷地找到所需的页面元素。文章也谈到了如何遍历搜索结果,使您可以逐个地处理元素。jQuery 的这两个方面是本系列下一篇文章的基础,同时也是所有 jQuery 代码的基础。










