Home > Web Front-end > JS Tutorial > document.getElementById的简写方式(获取id对象的简略写法)_基础知识

document.getElementById的简写方式(获取id对象的简略写法)_基础知识

WBOY
Release: 2016-05-16 18:19:58
Original
1928 people have browsed it

比如用_$(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.
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template