实现代码如下:

function $(id){return document.getElementById(id);

上面的对于新版本的浏览器都是没有问题的,如果使用古老的浏览器,可以使用下面的函数
实现代码如下:

function $(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
// W3C DOM
return document.getElementById(objectId);
}
else if (document.all && document.all(objectId)) {
// MSIE 4 DOM
return document.all(objectId);
}
else if (document.layers && document.layers[objectId]) {
// NN 4 DOM.. note: this won't find nested layers
return document.layers[objectId];
}
else {
return false;
}
}

来实现$代替document.getElementById的效果,虽然简单,但对于没有引用了prototype和jquery等框架的,避免了每次写document.getElementById,只需在一个公共JavaScript文件定义后便可处处使用了。

以上就是【JavaScript中也使用$美元符号来代替document.getElementById】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论