亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

一個獲取第n個元素節(jié)點的js函數(shù)

 更新時間:2014年09月02日 15:47:45   投稿:whsnow  
這篇文章主要介紹了一個獲取第n個元素節(jié)點的js函數(shù),功能還不完善 ,需要的朋友可以參考下

一個獲取第n個元素節(jié)點的函數(shù),現(xiàn)在只能通過html標簽獲取元素,功能還不完善

演示:html

<ul id="list">
<li>1<button>a</button></li>
<li>2<button>b</button><button>o</button></li>
<p>test</p>
<li>3<button>c</button></li>
<li>4<button>d</button></li>
<li>5<button>e</button></li>
</ul>

js:

/**
*
* @param parent父節(jié)點
* @param ele要選取的元素標簽
* @param num第幾個元素
* @return {*}
*/
function nth(parent,ele,num){
var _ele=Array.prototype.slice.call(parent.childNodes),eleArray=[];
//將父節(jié)點的子節(jié)點轉(zhuǎn)換成數(shù)組_ele;eleArray為只儲存元素節(jié)點的數(shù)組
for(var i= 0,len=_ele.length;i<len;i++){
if(_ele[i].nodeType==1){
eleArray.push(_ele[i]);//過濾掉非元素節(jié)點
}
}
if(arguments.length===2){
//如果只傳入2個參數(shù),則如果第二個參數(shù)是數(shù)字,則選取父節(jié)點下的第幾個元素
//如果第二個參數(shù)是字符串,則選取父節(jié)點下的所有參數(shù)代表的節(jié)點
if(typeof arguments[1]==="string"){
_ele=Array.prototype.slice.call(parent.getElementsByTagName(arguments[1]));
return _ele;
}else if(typeof arguments[1]==="number"){
return eleArray[arguments[1]];
}
}else{
//如果參數(shù)齊全,則返回第幾個某節(jié)點,索引從0開始
_ele=Array.prototype.slice.call(parent.getElementsByTagName(ele));
return _ele[num];
}
}
/*
測試
*/
var list=document.getElementById("list");
console.log(nth(list,"li",2).innerHTML);//選取第三個li元素
console.log(nth(list,"button",3).innerHTML)//選取第四個按鈕
console.log(nth(nth(list,"li",1),"button",1).innerHTML);//選取第二個li下的第二個按鈕
console.log(nth(nth(list,"li",1),"button"));//選取第二個li下的所有按鈕
console.log(nth(list,2));//選取第二個元素

相關(guān)文章

最新評論