JSRUN 用代码说话

应用程序

编辑教程

应用程序

本章演示一些基于 XML, HTML, XML DOM 和 JavaScript 构建的小型 XML 应用程序。

XML 文档实例

在本应用程序中,我们将使用 "cd_catalog.xml" 文件。

在 HTML div 元素中显示第一个 CD

下面的实例从第一个 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 时显示专辑信息

最后的实例展示如何在用户点击某个 CD 项目时显示专辑信息:

<!DOCTYPE html>
<html>
<head>
<script>
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","cd_catalog.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML; 
x=xmlDoc.getElementsByTagName("CD");

function displayCDInfo(i)
{
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);
country=(x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue);
company=(x[i].getElementsByTagName("COMPANY")[0].childNodes[0].nodeValue);
price=(x[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue);
txt="Artist: "+artist+"<br>Title: "+title+"<br>Year: "+year+"<br>Country: "+country+"<br>Company: "+company+"<br>Price: "+price  ;
document.getElementById("showCD").innerHTML=txt;
}
</script>
</head>

<body>
<div id='showCD'>Click on a CD to display album information.</div><br>
<script>
document.write("<table border='1'>");
for (var i=0;i<x.length;i++)
  { 
  document.write("<tr onclick='displayCDInfo(" + i + ")'>");
  document.write("<td>");
  document.write(x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue);
  document.write("</td><td>");
  document.write(x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue);
  document.write("</td></tr>");
  }
document.write("</table>");
</script>

</body>
</html>
JSRUN闪电教程系统是国内最先开创的教程维护系统, 所有工程师都可以参与共同维护的闪电教程,让知识的积累变得统一完整、自成体系。 大家可以一起参与进共编,让零散的知识点帮助更多的人。
X
支付宝
9.99
无法付款,请点击这里
金额: 0
备注:
转账时请填写正确的金额和备注信息,到账由人工处理,可能需要较长时间
如有疑问请联系QQ:565830900
正在生成二维码, 此过程可能需要15秒钟