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

 

转载于:https://www.cnblogs.com/wishyouhappy/p/3799911.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值