0
我想要在我的頁面上加載內容文件的導航按鈕,但其中一些文件是XML,需要用XSL轉換樣式。過去我使用XSL On the w3schools.com上的客戶端代碼取得了成功,所以我已經在下面進行了修改。然而,似乎沒有工作與我的JavaScript和jQuery的組合,或者我沒有正確傳遞參數? Firebug告訴我它無法加載'xsl'變量。這個語法看起來有什麼問題嗎?我對此非常陌生,無法弄清楚我做錯了什麼。混合JavaScript和jQuery與XSL轉換,或與函數參數的東西?
<script>
$(document).ready(function(){
$("#aboutTextButton").click(function(){
$('#contentContainer').load('about-text.html');
});
$("#aboutProjectButton").click(function(){
$('#contentContainer').load('about-project.html');
});
$("#catalogButton").click(function(){
displayResult("catalog.xml","xml-style2.xsl");
});
$("#transcriptionButton").click(function(){
displayResult("behaviour.xml","xml-style2.xsl");
});
});
//script to transform XML, adapted from w3schools.com
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
function displayResult(xml, xsl)
{
// code for IE
if (window.ActiveXObject)
{
ex=xml.transformNode(xsl);
document.getElementById("example").innerHTML=ex;
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml,document);
document.getElementById("contentContainer").appendChild(resultDocument);
}
}
</script>
</head>
<body>
<div id="headerImg">
<img src="cover.jpg">
</div>
<div id="menu">
<ul>
<li><a id="aboutTextButton">About the Text</a></li>
<li><a id="aboutProjectButton">About the Project</a></li>
<li><a id="catalogButton">Browse the Images</a></li>
<li><a id="transcriptionButton">Read the Text</a></li>
</ul>
</div>
<div id="contentContainer">
</div>
[見本頁](https://developer.mozilla.org/en/Using_the_Mozilla_JavaScript_interface_to_XSL_Transformations)在MDN網站上。您使用「.importStylesheet()」不正確。 – Pointy 2011-12-14 00:04:17
您通常不會看到通過javascript應用的XSL轉換。大多數情況下,它是在發送頁面之前在服務器上完成的,儘管可以直接將xml發送到瀏覽器,並讓瀏覽器使用如下處理指令處理xslt:`<?xml-stylesheet type =「text/xsl「href =」...「?>`......無論如何,真的沒有理由涉及JavaScript,因爲服務器端通常是首選方式,而客戶端(無javascript)xsl得到了很好的支持跨瀏覽器(即使ie6幾乎100%都可以),儘管很少使用。 – 2011-12-14 00:07:37