【问题标题】:Choosing the second element with XML Parsing with Jquery使用 Jquery 选择 XML Parsing 的第二个元素
【发布时间】:2017-12-14 03:54:21
【问题描述】:

我试图解析我的 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>

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery xml parsing


    【解决方案1】:

    使用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>");
    
        }
      });
    

    DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-01
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 2011-10-17
      • 1970-01-01
      • 2011-07-22
      • 1970-01-01
      相关资源
      最近更新 更多