栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

jQuery树遍历-将嵌套的无序列表元素嵌套到JSON

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

jQuery树遍历-将嵌套的无序列表元素嵌套到JSON

嗯,一个有趣的小递归练习。我花了一点时间,这就是我的做法。这可以递归地深入许多级别,但是假定您的数据不够深而无法爆炸内存(如果浏览器的深度太深,则递归会中断)。至少应保持10级左右的罚款。

我对此进行了测试,似乎可以正常工作,只需将其保存在HTML文件中就可以了。

抱歉,注释不太多(从技术上来说,没有任何注释:),这是假定您阅读jQuery和JS代码很好。如果您有任何疑问,请在评论中提问,我们乐于解释。

<!DOCTYPE HTML><html><head>    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />    <title>Recursive list processor example</title>    <script type="text/javascript" src="http://pre.jquery.com/jquery-1.4.2.min.js"></script>    <script type="text/javascript">$(document).ready(function() {    var out = [];    function processoneLi(node) {        var aNode = node.children("a:first");        var retVal = { "title": aNode.attr("title"), "url": aNode.attr("href"), "name": aNode.text()        };        node.find("> .children > li").each(function() { if (!retVal.hasOwnProperty("children")) {     retVal.children = []; } retVal.children.push(processoneLi($(this)));        });        return retVal;    }    $("#mycustomid").children("li").each(function() {        out.push(processoneLi($(this)));    });    console.log("got the following JSON from your HTML:", JSON.stringify(out));});    </script></head><body><ul id="mycustomid">    <li><a href="http://example.com/urlOfItemA" title="sometitle">Item A</a>        <ul ><li><a href="http://example.com/urlOfItemAChild1" title="sometitle">Child1 of A</a>    <ul >      <li><a href="http://example.com/urlOfItemAGrandchild" title="sometitle">Grandchild of A</a>         <ul > <li><a href="http://example.com/urlOfItemAGrandGrandChild" title="sometitle">Grand Grand child of A</a></li>         </ul>     </li>    </ul></li>        </ul>    </li>    <li><a href="http://example.com/urlOfItemB" title="sometitle2">Item '"" B</a></li>    <li><a href="http://example.com/urlOfItemC" title="sometitle3">Item C</a></li></ul></body></html>


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/404172.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号