比如用_$(id)代替document.getElementById(id).
如果是纯粹的代替可以使用下面的代码
function $(id){document.getElementById(id)}
个人比较推荐用prototype中对document.getElementById的定义:
function $()
{
var elements = new Array();
for (var i = 0; i {
var element = arguments[i];
if (typeof element == 'string')
element = document.getElementById(element);
if (arguments.length == 1)
return element;
elements.push(element);
}
return elements;
}
你还可以用以下代码来定义:
function $(objectId) {
if(document.getElementById && document.getElementById(objectId)) {
return document.getElementById(objectId);// W3C DOM
} else if (document.all && document.all(objectId)) {
return document.all(objectId);// MSIE 4 DOM
} else if (document.layers && document.layers[objectId]) {
return document.layers[objectId];// NN 4 DOM.. note: this won't find nested layers
} else {
return false;
}
}
这样写不断可以为JS文件省掉不少字符,还可以避免输入时的错误.
有一个小小的说明,$是一个自定义的值,你可以根据你的喜好写任何一个非JavaScript保留关键字,比如i_d,myid,等等你喜欢的定义.如果你的页面中调用到了jQuery的库文件,你可以直接用$代替document.getElementById.
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn