今天剛好遇到一個需要用jquery去做checbox出可以全選或是取消全選的功能,這樣的功能常出現在信箱管理,或者是購物清單等等。此做法雖然有很多多餘的句子,但至少還蠻好理解的..(對我來說xd )
我的作法:
$(function(){
$("input[type=checkbox]:eq(0)").click(function() {
if($("input[type=checkbox]:eq(0)").attr("checked"))
{
$("input[type=checkbox]:gt(0)").each(function() {
$(this).attr("checked", true);
});
}
else
{
$("input[type=checkbox]:gt(0)").each(function() {
$(this).attr("checked", false);
});
}
});
})
(有中文註解的)
$("input[type=checkbox]:eq(0)").click(function() {
//當第一個checkbox被click(按下)之後執行以下function
if($("input[type=checkbox]:eq(0)").attr("checked"))
//如果第一個checkbox已經有checked的屬性
{
$("input[type=checkbox]:gt(0)").each(function() {
$(this).attr("checked", true);
//那麼第0個(也就是畫面上的第一個checkbox)之後(gt(0))所有的(each)每個checkbox都讓他的屬性變成checked
});
}
else //不果第一個沒有checked屬性
{
$("input[type=checkbox]:gt(0)").each(function() {
$(this).attr("checked", false);
//那麼第0個(也就是畫面上的第一個checkbox)之後(gt(0))所有的(each)每個checkbox都讓他的屬性都是沒有checked
});
}
});
})

或許你的畫面不只一個form
也或許一個頁面有好幾個清單的控制
這時候使用$("input[type=checkbox]:eq(0)去找到第一個checkbox可能會有問題
因為若一個頁面有兩個form 那麼它只會選到第一個form的checkbox
所以我的做法就是讓他對到一個id
在 $("input[type=checkbox]:eq(0) 的input前面加上其可以對應到的id
如:
$(function(){
//如這個click function我讓它對到只作用在id=todo_list的checkbox
$("#todo_list input[type=checkbox]:eq(0)").click(function() {
if($("#todo_list input[type=checkbox]:eq(0)").attr("checked"))
{
$("#todo_list input[type=checkbox]:gt(0)").each(function() {
$(this).attr("checked", true);
});
}
else
{
$("#todo_list input[type=checkbox]:gt(0)").each(function() {
$(this).attr("checked", false);
});
}
});
})
練習原始檔rar:
https://docs.google.com/open?id=0Bzn3SuMe9TQGTHZhb1N4OFpnTFk
參考資料:
[jQuery]判斷 checkbox 是否選取,實現全選跟全部取消
魚乾的筆記本-query radiobox取值,checkbox取值,radio選中,checkbox選中,select選中,及其相關
資源:
若不清楚:gt( ) :eq( ) 等等如何使用:jQuery神奇的選擇器(Selector)

沒有留言:
張貼留言
若你看的文章,時間太久遠的問題就別問了,因為我應該也忘了... XD