zoukankan      html  css  js  c++  java
  • document.getElementById的简便方式

    封装自己的元素获取方法,使元素获取变得简便

    注意:1、应该要防止定义的被重写,可将同名的重新定义

         2、可将封装的对象置为全局对象,方便使用

    通过id查找单个元素


    封装方式:

    //通过id查找单个元素
    (function (document){
        //防止覆盖
        var _overwrite = window._,
            _;
    
        _ = {
            $ : function(id){
                return typeof id === "string" ? document.getElementById(id) : id;
            }
        }
    
        //将_置为全局对象
        window._ = _;
    
    })(document);

    测试:

    <!DOCTYPE html>
    <html>
    <body>
        <div id = "cloud">The cloud is beautiful</div>
    </body>
    <script><!--
    (function (document){
        //防止覆盖
        var _overwrite = window._,
            _;
    
        _ = {
            $ : function(id){
                return typeof id === "string" ? document.getElementById(id) : id;
            }
        }
    
        //将_置为全局对象
        window._ = _;
    
    })(document);
    
    
    var cloud = _.$("cloud");
    alert(cloud.innerHTML); //The cloud is beautiful
    --></script>
    </html>

    通过ID获取多个元素


    封装方式:

    //通过id查找一个或者多个元素
    (function (document){
        //防止覆盖
        var _overwrite = window._,
            _;
        _ = {
            $ : function(/*ids....*/){
                var elements = {},
                        id,
                        elt;
                for(var i = 0, len= arguments.length; i < len; i++){
                    id = arguments[i];
                    elt = document.getElementById(id);
                    if(elt === null){
                        throw new Error("No element with id:" + id);
                    }
                    if(len === 1){
                        return elt;
                    }
                    elements[id] = elt;
                }
                return elements;        
            }
        }
    
        //将_置为全局对象
        window._ = _;
    
    })(document);

    测试:

     <div id = "cloud">The cloud is beautiful</div>
     <div id = "sea">The white white sea</div>
    //获取单个元素
    var cloud = _.$("cloud");
    alert(cloud.innerHTML);//The cloud is beautiful
    
    //获取多个元素
    var all = _.$("cloud", "sea");
    alert(all.cloud.innerHTML + "," + all.sea.innerHTML); //The cloud is beautiful,The white white sea
    
  • 相关阅读:
    Linux rcp命令详解
    Linux patch命令详解
    Linux paste命令详解
    linux od命令详解
    linux mv命令详解
    Linux more命令详解
    Linux mktemp命令
    MySQL状态变量详解
    mysql性能分析show profile/show profiles
    MySQL执行计划
  • 原文地址:https://www.cnblogs.com/wishyouhappy/p/3799911.html
Copyright © 2011-2022 走看看