XML 注意事項(xiàng)
本節(jié)列出了您在使用 XML 時(shí)應(yīng)該盡量避免使用的技術(shù)。
Internet Explorer - XML 數(shù)據(jù)島
它是什么?XML 數(shù)據(jù)島(XML Data Islands)是嵌入 HTML 頁面中的 XML 數(shù)據(jù)。
為什么要避免使用它?XML 數(shù)據(jù)島只在 Internet Explorer 瀏覽器中有效。
用什么代替它?您應(yīng)當(dāng)在 HTML 中使用 JavaScript 和 XML DOM 來解析并顯示 XML。
如需更多有關(guān) JavaScript 和 XML DOM 的信息,請(qǐng)?jiān)L問 w3school 的 XML DOM 教程。
XML 數(shù)據(jù)島實(shí)例
本例使用 XML 文檔 "cd_catalog.xml"。
把 XML 文檔綁定到 HTML 文檔中的一個(gè) <xml> 標(biāo)簽。id 屬性定義數(shù)據(jù)島的標(biāo)識(shí)符,而 src 屬性指向 XML 文件:
<html>
<body>
<xml id="cdcat" src="cd_catalog.xml"></xml>
<table border="1" datasrc="#cdcat">
<tr>
<td><span datafld="ARTIST"></span></td>
<td><span datafld="TITLE"></span></td>
</tr>
</table>
</body>
</html>
<table> 標(biāo)簽的 datasrc 屬性把 HTML 表格綁定到 XML 數(shù)據(jù)島。
<span> 標(biāo)簽允許 datafld 屬性引用要顯示的 XML 元素。在這個(gè)例子中,要引用的是 "ARTIST" 和 "TITLE"。當(dāng)讀取 XML 時(shí),會(huì)為每個(gè) <CD> 元素創(chuàng)建相應(yīng)的表格行。
如果您正在使用 Internet Explorer,可以親自試一試。
Internet Explorer - 行為
它是什么?Internet Explorer 5 引入了行為(behaviors)。Behaviors 是通過使用 CSS 樣式向 XML (或 HTML )元素添加行為的一種方法。
為什么要避免使用它?只有 Internet Explorer 支持 behavior 屬性。
使用什么代替它?使用 JavaScript 和 XML DOM (或 HTML DOM)來代替它。
實(shí)例
例子 1 - Mouseover Highlight
下面的 HTML 文件中的 <style> 元素為 <h1> 元素定義了一個(gè)行為:
<html> <head> <style type="text/css"> h1 { behavior: url(behave.htc) } </style> </head> <body> <h1>Mouse over me!!!</h1> </body> </html>
以下是 XML 文檔 "behave.htc":
<attach for="element" event="onmouseover" handler="hig_lite" /> <attach for="element" event="onmouseout" handler="low_lite" /> <script type="text/javascript"> function hig_lite() { element.style.color='red'; } function low_lite() { element.style.color='blue'; } </script>
這個(gè) behavior 文件包含了一段 JavaScript,以及針對(duì)元素的事件句柄。
親自試一試 (請(qǐng)把鼠標(biāo)移到例子中的文本上)(請(qǐng)?jiān)?IE 瀏覽器中測(cè)試本例)。
例子 2 - 打字機(jī)模擬
下面的 HTML 文件中的 <style> 元素為 id 為 "typing" 的元素定義了一個(gè)行為:
<html> <head> <style type="text/css"> #typing { behavior:url(typing.htc); font-family:'courier new'; } </style> </head> <body> <span id="typing" speed="100">IE5 introduced DHTML behaviors. Behaviors are a way to add DHTML functionality to HTML elements with the ease of CSS.<br /><br />How do behaviors work?<br /> By using XML we can link behaviors to any element in a web page and manipulate that element.</p> </span> </body> </html>
以下是 XML 文檔 "typing.htc":
<attach for="window" event="onload" handler="beginTyping" /> <method name="type" /> <script type="text/javascript"> var i,text1,text2,textLength,t; function beginTyping() { i=0; text1=element.innerText; textLength=text1.length; element.innerText=""; text2=""; t=window.setInterval(element.id+".type()",speed); } function type() { text2=text2+text1.substring(i,i+1); element.innerText=text2; i=i+1; if (i==textLength) { clearInterval(t); } } </script>