现在的位置: 首页 > 综合 > 正文

JavaScript中也使用$美元符号来代替document.getElementById

2013年02月09日 ⁄ 综合 ⁄ 共 593字 ⁄ 字号 评论关闭

复制代码 代码如下:
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文件定义后便可处处使用了。

抱歉!评论已关闭.