zoukankan      html  css  js  c++  java
  • jquery中的each用法以及js中的each方法实现实例

    each()方法能使DOM循环结构简洁,不容易出错。each()函数封装了十分强大的遍历功能,使用也很方便,它可以遍历一维数组、多维数组、DOM, JSON 等等
    在javaScript开发过程中使用$each可以大大的减轻我们的工作量。

    下面提一下each的几种常用的用法

    each处理一维数组
    var arr1 = [ "aaa", "bbb", "ccc" ];      
      $.each(arr1, function(i,val){      
          alert(i);   
          alert(val);
      });   
    

     alert(i)将输出0,1,2
    alert(val)将输出aaa,bbb,ccc  

    each处理二维数组  

    var arr2 = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']]      
      $.each(arr2, function(i, item){      
          alert(i);   
          alert(item);      
      });  

    arr2为一个二维数组,item相当于取这二维数组中的每一个数组。
    item[0]相对于取每一个一维数组里的第一个值   
    alert(i)将输出为0,1,2,因为这二维数组含有3个数组元素
    alert(item)将输出为  ['a', 'aa', 'aaa'],['b', 'bb', 'bbb'],['c', 'cc', 'ccc']

    对此二位数组的处理稍作变更之后

    ar arr = [['a', 'aa', 'aaa'], ['b', 'bb', 'bbb'], ['c', 'cc', 'ccc']]      
       $.each(arr, function(i, item){      
            $.each(item,function(j,val){
                alert(j);
                alert(val);
         }); 
    });    

    alert(j)将输出为0,1,2,0,1,2,0,1,2

    alert(val)将输出为a,aa,aaa,b,bb,bbb,c,cc,ccc
     
     
    each处理json数据,这个each就有更厉害了,能循环每一个属性  
     
    var obj = { one:1, two:2, three:3};      
       $.each(obj, function(key, val) {      
            alert(key);   
            alert(val);      
       });   

    这里alert(key)将输出one two three
    alert(val)将输出one,1,two,2,three,3
    这边为何key不是数字而是属性呢,因为json格式内是一组无序的属性-值,既然无序,又何来数字呢。
    而这个val等同于obj[key]

    js中each实现,首先感谢豪情哥提供的跟随对联广告实例,让我有机会知道这么多我欠缺的知识点。代码里有我个人的理解标注了解释。

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>跟随对联广告-豪情</title>
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
        <style type="text/css">
            *{margin:0;padding:0;}
            body{ font:12px/1.125 Microsoft YaHei; background:#fff; }
            ul,li{list-style:none;}
            a{text-decoration:none;}
            .wrap{width:600px;height:350px;margin:10px auto;border:1px solid #ccc;}
            .inner{padding:15px;}
            .clearfix{overflow:hidden;_zoom:1;}
            .none{display:none;}
            .banner{width:100px;height:300px;position:absolute;top:200px;}
            .banner:nth-child(1){left:100px;}
            .banner:nth-child(2){right:100px;}
        </style>
    </head>
    <body>
    <div style="height:3000px"></div>
    <div style="display:none;">
        <div id="div" style="100px;height:200px;background:#000;"></div>
        <button id="btn">test</button>
    </div>
    <script>
        (function(){
        //dog是一个方法类 就是一个简短的自定义的类jquery库
            var dog = {
                $ : function(id){
                    return document.querySelector(id);
                },
                tpl : function(html, data){
                    return html.replace(/{{(w+)}}/g, function(item, a){
                        return data[a];
                    });
                },
                pos : function(obj, attr){
                    if(obj){
                        return obj.getBoundingClientRect()[attr];    
                    } else {
                        alert('对象不存在!');
                    }
                },
                viewSize: function(){
                    var de = document.documentElement;
                    var doc = document;
                    return {
                        'width': (window.innerWidth || (de && de.clientWidth) || doc.body.clientWidth),
                        'height': (window.innerHeight || (de && de.clientHeight) || doc.body.clientHeight)
                    };
                }(),
                on: function(el, type, handler){
                    el.addEventListener(type, handler, false);//监听事件
                },
                off: function(el, type, handler){
                    el.removeEventListener(type, handler, false);//移除监听
                },
                css : function(obj, attr){
                    if(obj.currentStyle){
                        return obj.currentStyle[attr];
                    } else {
                        return getComputedStyle(obj, false)[attr];
                    } 
                },
                act : function(obj, attr, target){
                    var that = this;
                    clearInterval(obj.timer);
                    obj.timer = setInterval(function(){
                        var stop = true;
                        var cur = parseInt(that.css(obj, attr));
                        var speed = (target - cur) / 8;
                        speed = speed < 0 ? Math.ceil(speed) : Math.floor(speed);
                        if(target != speed){
                            stop = false;
                        }
                        obj.style[attr] = speed + cur + 'px';
                        if(stop){
                            clearInterval(obj.timer);
                        }
                    }, 55);
                },
                //自己实现each方法
                each : function(arr, callback){//数组,回调函数 arr大约等于opt
                    if(Array.isArray(arr)){
                        for(var i = 0, l = arr.length; i < l; i++){
                        //出现false即出错情况下出现
                            if(callback.call(arr[i], i, arr[i++]) == false){//元素对象存在 i相当于下面function(i,m)中的i,arr[i++]相当于m
                                break;
                            }
                        }
                    } else {
                        for(var name in arr){
                            if(callback.call(arr[name], name, arr[name]) == false){//元素对象存在 name相当于下面function(i,m)中的i,arr[name]相当于m
                                break;
                            }
                        }
                    }
                },
                create : function(opt){//传入一个对象
                    var el = document.createElement(opt.tag || 'div');
                    this.each(opt, function(i, m){
                        el[i] = this;//
                    });
                    return el;
                }
            }
            function Adv(){
                var args = arguments[0];
                for(var i in args){
                    this[i] = args[i];
                }
                this.init();
            }
            Adv.prototype = {
                init : function(){
                    this.render();
                    this.bind();
                },
                render : function(){
                    var div = dog.create({ className : 'out'}),
                        a = dog.create({ className : 'banner'}),
                        b = null;
                    a.innerHTML = this.tpl;
                    b = a.cloneNode(true);
                    div.appendChild(a);
                    div.appendChild(b);
                    document.body.appendChild(div);
                    this.a = a;
                    this.b = b;
                },
                bind : function(){
                    var that = this,
                        doc = document,
                        scrollTop = 0,
                        t = 0;
                    //调用dog类
                    dog.on(window, 'scroll', function(){//监听scroll事件
                        scrollTop = doc.documentElement.scrollTop || doc.body.scrollTop;
                        t = scrollTop + (doc.documentElement.clientHeight - that.a.offsetHeight) / 2;
                        dog.act(that.a, 'top', t);
                        dog.act(that.b, 'top', t);
                    });
                },
                getDom : function(){
                    
                }
            }
            var defaults = {
                id : 'dialog',
                tpl : '<img src="images/ad.jpg" alt="">'
            }
            new Adv(defaults);
        }());
    </script>
    </body>
    </html>

    自己做到demo理解

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>test</title>
        
    </head>
    <body>
    <div id="xid">dddddddddddddd</div>
    </body>
    <script type="text/javascript" language="javascript">
        (function(){
         var test={
          $:function(id){
          return document.querySelector(id);
          },
          xx:function(obj){
          //alert(obj);
           var obd= document.getElementById(obj);
          // obd.innerHTML="wo test";
          obd.style.backgroundColor='red';
          }
         }
         function demo(){
            var args = arguments[0];
                for(var i in args){
                    this[i] = args[i];
                }
                this.init();
         }
          demo.prototype = {
                init : function(){
                    this.render();
                },
                render : function(){
                var that =this;
                // alert(that.id));
                 var b= test.xx(that.id);
                }
        }
         var test2={
            id:'xid'
         };
            new demo(test2);    
        })();
        </script>
    </html>
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>test</title>
        
    </head>
    <body>
    <div id="xid"  style="200px; height:230px;">dddddddddddddd</div>
    </body>
    <script type="text/javascript" language="javascript">
    //HTML DOM querySelector()  关键是这个方法的语法和用法
        (function(){
         var test={
          $:function(id){
          return document.querySelector(id);
          },
          xx:function(){ 
           //that.abc()
           //alert(that.id);
           //var obd= document.getElementById(that.id);
          // obd.innerHTML="wo test";
          
          //obd.style.backgroundColor='red';
          },
          css : function(obj, attr){
                    if(obj.currentStyle){
                        return obj.currentStyle[attr];
                    } else {
                        return getComputedStyle(obj, false)[attr];
                    } 
                },
         }
         function demo(){
            var args = arguments[0];
                for(var i in args){
                    this[i] = args[i];
                }
                this.init();
         }
          demo.prototype = {
                init : function(){
                    this.render();
                },
                render : function(){
                 var that=this;
                 var target=test.$("#"+that.id);
                 target.style.backgroundColor='red';
                 alert(test.css(target,'width'));
                }
        }
         var dddd={
            id:'xid'
         };
            new demo(dddd);    
        })();
        </script>
    </html>

    由于对js了解甚少,又不知道从哪些地方入手,于是打算从理解+模仿来学习。希望有所获。

    模仿学习案例链接:http://www.kancloud.cn/jikeytang/qq/81141

     
     
  • 相关阅读:
    Spiral Matrix
    Merge Intervals
    Edit Distance
    Insertion Sort List
    Add Binary
    Partition List
    Binary Tree Postorder Traversal
    单向链表反转
    Facebook Hacker cup Qualification round Problem 1
    判断二叉树是否为平衡二叉树
  • 原文地址:https://www.cnblogs.com/xiaohuasan/p/5490108.html
Copyright © 2011-2022 走看看