利用Array Prototype的方法来实现对dom集合的筛选、indexOf、map等功能

  1. <!DOCTYPE html><html>
        <head>
            <title>TODO supply a title</title>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <style type="text/css">
                div{background-color:red;margin:10px;}
            </style>
        </head>
        <body>
            <div class="w50" style="width:50px;height:20px"></div>
            <div class="w20" style="width:20px;height:20px"></div>
            <div class="w30" id="test" style="width:30px;height:20px"></div>
            <div class="w40" style="width:40px;height:20px"></div>
            <div class="w10" style="width:10px;height:20px"></div>
        </body>
    </html>

     

    var arrPro = Array.prototype;
    var core_filter = arrPro.filter;
    var core_indexOf = arrPro.indexOf;
    var core_slide = arrPro.slice;
    var core_sort = arrPro.sort;
    var core_map  = arrPro.map;
    
    //当然 为了兼容,应该有toArray方法,对不支持slice.call(nodeList)的浏览器,使用循环
    var divArr = core_slide.call(document.getElementsByTagName('div'));
    
    console.log('筛选出所有宽度小于等于30px的div',core_filter.call(divArr,function(item,index){                
        return parseInt(item.style.width,10) <= 30;
    }));
    console.log('获取#test元素的索引',core_indexOf.call(divArr,document.getElementById('test')));
    console.log('按照宽度倒叙排序',core_sort.call(divArr,function(a,b){
        return parseInt(a.style.width,10) < parseInt(b.style.width,10);
    }));
    //将所有div背景色改为黑色
    core_map.call(divArr,function(item){
        item.style.backgroundColor = 'black';
    });

    firebug截图:

posted @ 2014-04-09 11:30  henry_li  阅读(338)  评论(0编辑  收藏  举报