本章示範一些基於XML, HTML, XML DOM 和JavaScript 建構的小型XML 應用程式。
在本應用程式中,我們將使用"cd_catalog.xml" 檔案。
下面的實例從第一個CD 元素中取得XML 數據,然後在id="showCD" 的HTML 元素中顯示數據。 displayCD() 函數在頁面載入時呼叫:
x=xmlDoc.getElementsByTagName("CD");
i=0;
function displayCD()
{
artist=(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
title=(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
year=(x[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue);
txt="Artist: " + artist + "<br />Title: " + title + "<br />Year: "+ year;
document.getElementById("showCD").innerHTML=txt;
}
試試一下»
為了在上面的實例中添加導航(功能),需要建立next() 和previous() 兩個函數:
function next()
{ // display the next CD, unless you are on the last CD
if (i<x.length-1)
{
i++;
displayCD();
}
}
function previous()
{ // displays the previous CD, unless you are on the first CD
if (i>0)
{
i--;
displayCD();
}
}
試試一下»
最後的範例展示如何在使用者點擊某個CD 專案時顯示專輯資訊:
嘗試一下。
如需了解更多關於使用JavaScript 和XML DOM 的信息,請造訪我們的XML DOM 教學。