本章演示一些基于 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(); } }
運行實例 ?
點擊 "運行實例" 按鈕查看在線實例
當點擊 CD 時顯示專輯信息
最后的實例展示如何在用戶點擊某個 CD 項目時顯示專輯信息:
嘗試一下。
如需了解更多關(guān)于使用 JavaScript 和 XML DOM 的信息,請訪問我們的 XML DOM 教程。