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