我想将.each
方法中创建的元素包装在div
中。
这是我的代码:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "xml/timeline.xml",
dataType: "xml",
success: parseXML
});
function parseXML(xml) {
$(xml).find("Year").each(function() {
var year = $(this).attr("year");
$(".timeLineWrapper").append('<h2 class="timeYearHead">' + year + "</h2>");
$(this).find("Event").each(function() {
var event = $(this).text();
$(".timeLineWrapper").append('<p>' + event + '</p>');
}); // close find Event
}); // close find Year
} // close parseXML
}); // Close docDotReady
</script>
基本思路是为每年创建一个标题,并在该列表下面列出每年的事件,其中将有不同的数字。我希望在从XML文件解析后将事件包装在div
中。我该怎么做?
答案 0 :(得分:0)
这是我目前的剧本:
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: "xml/timeline.xml",
dataType: "xml",
success: parseXML
});
function parseXML(xml){
$(xml).find("Year").each(function(){
var year = $(this).attr("year");
$(".timeLine").append('<li class="timeYear"><h2 class="timeYearHead">' + year + "</h2></li>");
$(this).find("Event").each(function(){
var event = $(this).text();
$(".timeLine").append('<li class="timeEvent">' + event + '</li>');
}); // close find Event
}); // close find Year
} // close parseXML
}); // Close docDotReady
</script>
这是它产生的HTML输出:
<ul class="timeLine">
<li class="timeYear">
<h2 class="timeYearHead">1950</h2>
</li>
<li class="timeEvent">
One
</li>
<li class="timeEvent">
Two
</li>
<li class="timeEvent">
Three
</li>
<li class="timeEvent">
Four
</li>
<li class="timeYear">
<h2 class="timeYearHead">1951</h2>
</li>
<li class="timeEvent">
Five
</li>
<li class="timeEvent">
Six
</li>
<li class="timeEvent">
Seven
</li>
<li class="timeYear">
<h2 class="timeYearHead">1952</h2>
</li>
<li class="timeEvent">
Eight
</li>
<li class="timeEvent">
Nine
</li>
<li class="timeEvent">
Ten
</li>
<li class="timeEvent">
Eleven
</li>
<li class="timeEvent">
Twelve
</li>
</ul>
基本上,我正在尝试解析这个XML文件:
<?xml version="1.0"?>
<Years>
<Year year="1950">
<Events>
<Event>
One
</Event>
<Event>
Two
</Event>
<Event>
Three
</Event>
<Event>
Four
</Event>
</Events>
</Year>
<Year year="1951">
<Events>
<Event>
Five
</Event>
<Event>
Six
</Event>
<Event>
Seven
</Event>
</Events>
</Year>
<Year year="1952">
<Events>
<Event>
Eight
</Event>
<Event>
Nine
</Event>
<Event>
Ten
</Event>
<Event>
Eleven
</Event>
<Event>
Twelve
</Event>
</Events>
</Year>
</Years>
我的目标是在XML文件中为每年创建一个带有a的内容,其中包含与该年度相对应的每个事件列表的子列表以及该列表上的每个事件。