2011-06-13 4 views
0

jQuery를 사용하여 music.xml이라는 XML 파일 내용의 첫 번째 항목을 읽은 다음 DIV에서 5 초 동안 표시하고 다음 XML을 읽는 방법 항목을 표시하고 5 초 동안 표시하면 XML 파일을 반복 한 다음 처음부터 다시 시작 하시겠습니까?jQuery를 사용하여 XML 파일의 내용을 HTML로 순차적으로로드하는 방법

HTML :

<div id="music"> 
    <div id="albumcover"></div> 
    <div id="songdescription"></div> 
</div> 

music.xml

<songs> 
    <item> 
     <image>music_01.jpg</image> 
     <description>Description of first song</description> 
    </item> 
    <item> 
     <image>music_02.jpg</image> 
     <description>Description of second song</description> 
    </item> 
    <item> 
     <image>music_03.jpg</image> 
     <description>Description of third song</description> 
    </item> 
</songs> 
+0

그 'music.xml'파일은 어디에 있습니까? –

+0

HTML 파일과 모든 JPG와 동일한 디렉토리에 있습니다 –

답변

1

첫째, 나는 image 태그에 문제가 줄 것이다 jQuery를 사용하여 이러한 구문 분석하는 방법을 알고 방법 (편집 : 텍스트를 구문 분석 할 경우에만를, XML이 좋은 것으로 판명) 당신이 그것을 포장 한 번으로, jQuery는 <image>text</image><img>text으로 변환합니다. 당신은 그걸 처리 할 수는 있지만 꽤 예쁘지는 않습니다. 이제 <image>의 이름을 <cover>으로 변경했다고 가정 해 보겠습니다.

작동 jsFiddle, 빼기 $.ajax 요청 부분.

var music = []; 
var musicIndex = -1; 
var delay = 5000; 
var intervalId; // in case you want to clearInterval 
var $cover = $("#albumcover"); 
var $desc = $("#songdescription"); 

function rotateMusic() { 
    // Loop back to the beginning if necessary 
    if (++musicIndex === music.length) { 
    musicIndex = 0; 
    } 
    console.log(music[musicIndex].cover); 

    // Create a new image, tell it to append itself and description 
    // once it's loaded, tell it to load 
    $("<img>").load(function() { 
    $cover.empty().append($(this)); 
    $desc.text(music[musicIndex].desc); 
    }).attr("src", music[musicIndex].cover); 
} 

$.ajax({ 
    type: "GET", 
    url: "music.xml", 
    dataType: "xml", 
    success: function(xml) { 
      // Parse each item as a node 
      $(xml).find('item').each(function() { 
       // Add contents of item to music array 
       var $item = $(this); 
       music.push({ 
       cover: $item.find('image').text(), 
       desc: $item.find('description').text() 
       }); 

      }); 
      // Start rotating music, then set it to a delay 
      rotateMusic(); 
      intervalId = setInterval(rotateMusic, delay); 
      } 
}); 
+0

어딘가에 버그가 있습니다. 전체 JS가 $ (document) .ready 아래에서 실행되도록하고 두 번째 이미지와 세 번째 설명에서 회전을 중지합니다. –

+1

몇 가지 수정 사항을 수정해야합니다. 특히, 나는'$ (xml) ... each 문 밖에서'rotateMusic' 호출을 옮겨야했다. – brymck

+0

멋진, 그게 고정 –

2

이 같은 시도 :

$.ajax({ 
    'dataType': 'xml', 
    'success': function(xml) 
    { 
    $(xml).find('item').each(function() 
    { 
     var image = $(this).find('image').text(); 
     var description = $(this).find('description').text(); 

     $('<div id="music" />') 
     .append($('<div id="albumcover" />').append($('<img />').attr('src', image))) 
     .append($('<div id="songdescription" />').text(description)) 
     .appendTo('body'); 
    }); 

    // Add the code for the carousel here. 
    }, 
    'type': 'get', 
    'url': 'music.xml' 
}); 

당신은 XML 파일 (경로를 조정해야하고 어디에 이미지가 위치 함) 및 문서에 추가 할 위치를 지정합니다. 현재는 닫는 BODY 요소 바로 앞에 추가됩니다.

그런 다음 해당 부분을 처리하지 말고 순환 게재되는 회전식 jQuery 플러그인을 찾아 보시기 바랍니다. jCarousel Lite을 확인해야합니다.

+0

xml 파일이 HTML 파일 및 이미지와 동일한 폴더에 있으면 위의 스크립트에서 경로를 조정할 필요가 없습니다. –

+0

jQuery는 하나의 주석으로'$ (" text")'을 '[, "text"]'로 구문 분석합니다. 즉, "텍스트"는''(중요하게는 ''이 아닌)이지만 형제는 자식이 아닙니다. 따라서 xml.replace (/ image/i, "cover")와 같은 것일지라도이를 대체하고 싶을 것입니다. 나머지는 멋지게 작동한다고 생각합니다. – brymck

+0

@Bryan : 위의 코드를 사용하여 여기 내 컴퓨터에서 테스트했습니다. 정상적으로 작동했습니다. jQuery는 당신이 제안한대로'$ (" text")'응답을 변경하지 않았다. –

관련 문제