jquery操作復選框(checkbox)的一些小技巧總結


1、獲取單個checkbox選中項(三種寫法)

//第一種
$("input:checkbox:checked").val()
//第二種
$("input:[type='checkbox']:checked").val();
//第三種
$("input:[name='ck']:checked").val();

2、 獲取多個checkbox選中項

$('input:checkbox').each(function() {
        if ($(this).attr('checked') ==true) {
                alert($(this).val());
        }
});

3、設置第一個checkbox 為選中值

//第一種
$('input:checkbox:first').attr("checked",'checked');
//第二種
$('input:checkbox').eq(0).attr("checked",'true');

4、設置最后一個checkbox為選中值

//第一種
$('input:radio:last').attr('checked', 'checked');
//第二種
$('input:radio:last').attr('checked', 'true');

5、根據索引值設置任意一個checkbox為選中值

//第一種
$('input:checkbox).eq(索引值).attr('checked', 'true');索引值=0,1,2....
//第二種
$('input:radio').slice(1,2).attr('checked', 'true');

6、選中多個checkbox同時選中第1個和第2個的checkbox

$('input:radio').slice(0,2).attr('checked','true');

7、根據Value值設置checkbox為選中值

$("input:checkbox[value='1']").attr('checked','true');

8、刪除Value=1的checkbox

$("input:checkbox[value='1']").remove();

9、刪除第幾個checkbox

$("input:checkbox").eq(索引值).remove();//索引值=0,1,2....
//如刪除第3個checkbox:
$("input:checkbox").eq(2).remove();

10、遍歷checkbox

$('input:checkbox').each(function (index, domEle) {
//寫入代碼
});

11、全部選中

$('input:checkbox').each(function() {
        $(this).attr('checked', true);
});

12、全部取消選擇

$('input:checkbox').each(function () {
        $(this).attr('checked',false);
});

13、checkbox標簽已有checked=checked但是不顯示勾選

checkbox標簽已有checked=checked但是不顯示勾選,解決辦法就是將   $("...").attr("checked", true)改為$("...").prop("checked", true)

  JQuey中的 attr()函數和prop()函數,attr()是處理 attribute的值的,而prop()是處理 property 的值的 ,jQuery 1.6之前 ,.attr()方法在取某些 attribute 的值時,會返回 property 的值,這就導致了結果的不一致。從 jQuery 1.6 開始, .prop()方法 方法返回 property 的值,而 .attr() 方法返回 attributes 的值,那么歸根結底,就是在處理 attribute 和 property。
        很多attribute節點有一個相應的property屬性,因而attribute和property很容易被混淆在一起,如某個div元素中的id和class既是attribute也有property,不管哪種方式都可以訪問和修改,但是對於自定義的attribute節點,或者自定義property,兩者就沒有關系了(但是在IE6-7中,兩者還是一樣的,但願我們都能早日拋棄IE8以下的),需要注意的是,對於checked特性(attribute)不是對應它checked屬性(property),attribute實際對應的是defaultChecked屬性,而且僅用於設置復選框最初的值,checked的attribute不會因為復選框的狀態而改變,而checked的property會因為復選框的狀態而改變,所以在.attr()函數中,就算設置成了.attr("checked", true),也只是用來存儲默認或者選中屬性的默認值,卻並不改變該復選框被選中和選中,這就是為什么   checkbox標簽已有checked=checked但是不顯示勾選 的原因所在。

//.attr('checked');看版本1.6+返回:”checked”或”undefined” ;1.5-返回:true或false
//.prop('checked'); //16+:true/false
//.is(':checked'); //所有版本:true/false//別忘記冒號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM