我尝试解析我的 XML 文件。它有效,但我只想解析第二个歌曲元素。我怎样才能做到这一点?
我尝试修改和更改.each,但没有成功...
XML 文件
<?xml version="1.0" encoding="utf-8"?>
<Event status="happened">
<Song title="GOODBYE (FEAT. LYSE)">
<Artist name="FEDER">
</Artist>
<Info StartTime="23:10:54" ID="333" />
</Song>
<Song title="HOW YOU REMIND ME">
<Artist name="NICKELBACK">
</Artist>
<Info StartTime="23:15:49" ID="295" />
</Song>
</Event>
jQuery 脚本
<script>
$(document).ready(function(){
var myObj = {};
$.ajax({
type: "GET",
url: "Play.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Song').each(function(){
myObj.title = $(this).attr('title');
$(this).find('Artist').each(function(){
myObj.artist = $(this).attr('name');
});
$(this).find('Info').each(function(){
myObj.time = $(this).attr('StartTime');
myObj.id = $(this).attr('ID');
});
$('.history').append( "<div><img src='/covers/"+myObj.id+".jpg'></div><div class='style=float:left'><div class='time'>"+myObj.time+" {"+myObj.id+"}</div><div class='artist'>"+myObj.artist+"</div><div class='title'>"+myObj.title+"</div></div>" );
});
}
});
});
</script>
<div class="history"></div>
感谢您的帮助!
最佳答案
使用 eq()
通过索引获取歌曲元素。然后,对于每个子项,您不需要 each
,因为每个标签只有一个
$.ajax({
type: "GET",
url: "Play.xml",
dataType: "xml",
success: function(xml) {
var $song = $(xml).find('Song').eq(1),
$info = $song.find('Info'),
$artist = $song.find('Artist');
var myObj = {
title: $song.attr('title'),
artist: $artist.attr('name'),
time: $info.attr('StartTime'),
id: $info.attr('ID')
};
$('.history').append("<div><img src='/covers/" + myObj.id + ".jpg'></div><div class='style=float:left'><div class='time'>" + myObj.time + " {" + myObj.id + "}</div><div class='artist'>" + myObj.artist + "</div><div class='title'>" + myObj.title + "</div></div>");
}
});
关于javascript - 使用 Jquery 通过 XML 解析选择第二个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47805654/