gpt4 book ai didi

javascript - 将xml嵌套到jquery中的无序列表中

转载 作者:行者123 更新时间:2023-11-30 13:14:15 25 4
gpt4 key购买 nike

我正在尝试使用 jquery 将嵌套的 xml 文档转换为无序列表。xml 文档是

    <?xml version="1.0" encoding="utf-8"?>
<Parent>
<name>Director</name>
<Children>Exe Director1</Children>
<Children>Exe Director2</Children>
<Parent>
<name>Exe Director3</name>
<Children>Sub Director 1</Children>
<Children>Sub Director 2</Children>
<Parent>
<name>Sub Director 3</name>
<Children>Cameraman 1</Children>
<Children>Cameraman 2</Children>
</Parent>
</Parent>
</Parent>

预期输出:

 <ul>
<li>Director
<ul>
<li>Exe Director 1</li>
<li>Exe Director 2</li>
<li>Exe Director 3
<ul>
<li>Sub Director 1</li>
<li>Sub Director 2</li>
<li>Sub Director 3
<ul>
<li>Cameraman 1</li>
<li>Cameraman 2</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

我得到的输出。

 <ul>
<li>Director</li>
<ul>
<li>Exe Director1</li>
<li>Exe Director2</li>
<li>Exe Director3</li>
<ul>
<li>Sub Director 1</li>
<li>Sub Director 2</li>
<li>Sub Director 3</li>
<ul>
<li>Cameraman 1</li>
<li>Cameraman 2</li>
</ul>
</ul>
</ul>
</ul>

如您所见,子级不是在父级 li 内部而是在其外部创建的最新版代码

    <!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var levels;
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "test.xml",
dataType: "xml",
success: function (xml) {
var $ul = xmlParser(xml, $('#ListContainer'));
}
});
});

function xmlParser(xml,ul) {
$(xml).contents().each(function (i, el)
{
if (el.nodeName.toUpperCase() == "CHILDREN")
{
$("<li>").text($(el).text()).appendTo($('ul:last')); // Append <li> Children
} else if (el.nodeName.toUpperCase() == "NAME")
{
$('<li>').text($(el).text()).appendTo(ul);
$('<ul>').insertAfter($("li:last"));
}
else if (el.nodeName.toUpperCase() == "PARENT")
{
if($('ul').length == 0)
{
ul = ul.append('<ul>');
}
ul.append(xmlParser($(el),$("ul:last") )); // Recursively append the other Parent
}
});
return ul;
}
</script>
</head>
<body>
<div id="ListContainer"></div>
</body>
</html>

这段代码让我很头疼。你们能帮我解决可能出错的地方吗!

谢谢

最佳答案

您正在将 PARENT 元素附加到所有“PARENT”内容的相同“ul”元素。使用

 $ul.find('li').last().append(xmlParser($(el)));

代替

 $ul.append(xmlParser($(el)));

请引用以下链接获取最后一个 api:

http://api.jquery.com/last/

关于javascript - 将xml嵌套到jquery中的无序列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12704470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com