DIV CSS 佈局教程網

用 for 迴圈遍歷子節點查找元素的 JS 技巧
編輯:關於JavaScript     

本文介紹如何運用 JavaScript 的 for 迴圈搭配子節點遍歷,逐層查找目標元素,在處理嵌套 DOM 結構時相當實用。

 function nextChildNode(node,clazz,tagName){ var count= node.childElementCount; for(var i=0;i<count;i++){ if(node==undefined || node.children[i]==undefined){ continue; } if(clazz){ if(node.children[i].getAttribute('class')==clazz){ return node.children[i]; } }else{ if(node.children[i].tagName==tagName){ return node.children[i]; } } } return null; } function getChildNode(node,classArg,tagNodeArg){ for(var i=0;i<classArg.length;i++){ node=nextChildNode(node,classArg[i]); } for(var i=0;i<tagNodeArg.length;i++){ node=nextChildNode(node,null,tagNodeArg[i]); } return node; } function getItemId(node){ var classNode=['itemInfo','itemDesc'],tagNode=['P','BUTTON']; node=getChildNode(node,classNode,tagNode); alert(node.getAttribute('itemid')); } //調用函數 getItemId($(".shopItem")[0]);

這段程式碼透過 nextChildNode 逐一比對子節點的 class 或標籤名稱,再由 getChildNode 分層遞進,最終定位到目標元素並讀取其屬性,展現了 DOM 遍歷的靈活用法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved