JS获取对象代码总结
作者:sunxiaobo2008 来源:经典论坛 时间:2011-03-07 16:14:00
如果不用类库(如jquery)来写,往往很多时候,都需要通过id或tag来获取html里的某一对象,然后对其进行操作。
为了节省代码,把常用的获取对象的方法集成到函数里,每次直接通过传递参数来调用,可以是代码更简洁。下面总结了一下常用的获取对象的方法,供参考。
function GetId(id){return document.getElementById(id)} //通过ID获取对象
function GetTag(tag){return document.getElementsByTagName(tag)} //通过Tag获取对象(html标签名称)
function GetChildTag(id,tag){return id.getElementsByTagName(tag)} //通过Tag获取某ID对象的子对象
function GetClass(className){return getElementsByClassName(className)} //通过className获取对象
var $c=function(array){var nArray = [];for (var i=0;i<array.length;i++) nArray.push(array[i]);return nArray;};
Array.prototype.each=function(func){for(var i=0,l=this.length;i<l;i++) {func(this[i],i);};};
var getElementsByClassName=function(cn){
var hasClass=function(w,Name){
var hasClass = false;
w.className.split(' ').each(function(s){
if (s == Name) hasClass = true;
});
return hasClass;
};
var elems =document.getElementsByTagName("*")||document.all;
var elemList = [];
$c(elems).each(function(e){
if(hasClass(e,cn)){elemList.push(e);}
})
return $c(elemList);
};
上面代码里通过className获取对象的代码参考了论坛的一篇帖子,在此表示感谢。
使用方法示例:
[提示:你可先修改部分代码,再按运行]
部分HTML代码:
<div id="test" title="这是id=test的div">
<ul title="div内第一个ul">
<li>ccontent1</li>
<li>ccontent2</li>
<li>ccontent3</li>
<li>ccontent4</li>
</ul>
<ul class="test2" title="div内第二个ul,class=test2">
<li>bcontent1</li>
<li>bcontent2</li>
<li>bcontent3</li>
</ul>
</div>
<ul class="test2" title="div外的ul,class=test2">
<li>content1</li>
<li>content2</li>
</ul>
<input type="button" value="通过id获取" />
<input type="button" value="通过tag获取" />
<input type="button" value="通过id内tag获取" />
<input type="button" value="通过className获取" />
JS绑定事件:
window.onload=function(){
GetTag("input")[0].onclick=function(){alert("id为test的div内容是:"+GetId("test").innerHTML)}
GetTag("input")[1].onclick=function(){alert("body里共有"+GetTag("li").length+"个li")}
GetTag("input")[2].onclick=function(){alert("DIV里共有"+GetChildTag(GetId("test"),"li").length+"个li")}
GetTag("input")[3].onclick=function(){alert("className为test2的内容是:"+GetClass("test2")[0].innerHTML+GetClass("test2")[1].innerHTML)}
}
当然上面的函数名你还可以再简写,比如百度里获取id对象的函数就是这样的:
function G(id){return document.getElementById(id)} //调用方式:G("test")
或者这样:function $(id){return document.getElementById(id)} //$("test")