zoukankan      html  css  js  c++  java
  • 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);

      });

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

  • 相关阅读:
    1. 首次运行 Git 的配置
    本地git连接github
    Cygwin(linux)中vim配置
    ibatis入门
    XML(可扩展性标记语言)学习汇总一
    第一只小啊小爬虫(纪念下)
    Android SQLite DB的封装
    关于做项目的一些感想
    Git 初学三(git对象与git重置)
    Git 初学二(暂存区)
  • 原文地址:https://www.cnblogs.com/farwish/p/3800060.html
Copyright © 2011-2022 走看看