本文介绍如何在JavaScript中通过封装$函数来简化document.getElementById的调用。针对现代浏览器提供简洁实现,并为兼容古老浏览器(如MSIE 4、NN 4)提供包含document.all和document.layers检测的完整代码,避免引入prototype或jquery框架。
JavaScript中$符号封装示例
代码如下:
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等框架的项目,只需在公共JavaScript文件中定义一次,即可全局使用,避免了重复编写document.getElementById的繁琐工作。