checkbox中jQuery对数组和对象的操作

------------------------------------------------------------------------------------------

来段小例子,jQuery实现对表单中checkbox的全选/取消/反选

-------------------------@chenwei <www.farwish.com>---------------------------

<input type="checkbox" class="all" />

<input type="checkbox" name="id[]" value="1" />a

<input type="checkbox" name="id[]" value="2" />b

<input type="checkbox" name="id[]" value="3" />c

<button class="selectInverse">反选</button>

<script>

  $('.all').toggle(

    function({

      $(":input[name=id[]]").each(function(){

        $(this).attr('checked', true);

      });

    }),

    function({  

      $(":input[name=id[]]").each(function(){

        $(this).attr('checked', false);

      });

    })

  );

 

  $('.selectInverse').click(function(){

    $(":input[name=id[]]").each(function(){

      $(this).attr('checked', !this.checked);

    });

  });

</script>

-----------------------------------------------------------------------------------------

以上用到了事件:click, 事件切换:toggle, 表单元素的匹配:input, 设置元素的属性:attr, 数组和对象操作:each;

$().each();专门用于遍历jQuery对象;

$.each(object , [callback]) 是jQuery通用遍历方法,可用于遍历对象和数组;

例子:

  1.遍历数组,同时使用元素索引和内容

  $.each([0,1,2], function(i, n){

    console.log('item:'+ i +',value:'+ n);

  });

  2.遍历对象,同时使用成员名称和变量内容

  $.each({name:'chenwei', age:'81'}, function(i, n){

    console.log('name:'+ i + ', age:'+ n);

  });

-----------------------------------------------------------------------------------------

转载于:https://www.cnblogs.com/farwish/p/3800060.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值