XML 應(yīng)用程序

2018-02-09 17:47 更新

XML 應(yīng)用程序


本章演示一些基于 XML, HTML, XML DOM 和 JavaScript 構(gòu)建的小型 XML 應(yīng)用程序。


XML 文檔實例

在本應(yīng)用程序中,我們將使用 "cd_catalog.xml" 文件。


在 HTML div 元素中顯示第一個 CD

下面的實例從第一個 CD 元素中獲取 XML 數(shù)據(jù),然后在 id="showCD" 的 HTML 元素中顯示數(shù)據(jù)。displayCD() 函數(shù)在頁面加載時調(diào)用:

實例

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;
}

嘗試一下 ?


添加導(dǎo)航腳本

為了向上面的實例添加導(dǎo)航(功能),需要創(chuàng)建 next() 和 previous() 兩個函數(shù):

實例

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();
}
}

嘗試一下 ?


當(dāng)點擊 CD 時顯示專輯信息

最后的實例展示如何在用戶點擊某個 CD 項目時顯示專輯信息:

嘗試一下。

如需了解更多關(guān)于使用 JavaScript 和 XML DOM 的信息,請訪問我們的 XML DOM 教程。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號