XSLTProcessor: setParameter() 方法
XSLTProcessor 介面的 setParameter() 方法用於設定處理器中匯入的樣式表(<xsl:param>)的引數值。
語法
js
setParameter(namespaceURI, localName, value)
引數
namespaceURI-
與引數名稱關聯的名稱空間。 "null" 值被視為與空字串 (
"") 相同。 localName-
關聯名稱空間中的引數名稱。
value-
引數的值。
注意: Firefox 支援任何型別的引數。Chrome, Edge 和 Safari 只支援字串引數。
返回值
無(undefined)。
示例
使用 setParameter()
此示例演示瞭如何使用 setParameter() 將引數從 JavaScript 傳遞到 XSLT 樣式表,從而允許根據這些引數動態修改轉換輸出。
HTML
html
<div id="result"></div>
JavaScript
js
const xmlString = `
<items>
<item>Item 1</item>
<item>Item 2</item>
<item>Item 3</item>
</items>
`;
const xsltString = `
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:param name="showItems" select="'yes'"/>
<xsl:param name="highlightColor" select="'yellow'"/>
<xsl:template match="/">
<ul>
<xsl:if test="$showItems = 'yes'">
<xsl:for-each select="items/item">
<li style="background-color: {$highlightColor};">
<xsl:value-of select="."/>
</li>
</xsl:for-each>
</xsl:if>
</ul>
</xsl:template>
</xsl:stylesheet>
`;
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlString, "application/xml");
const xsltDoc = parser.parseFromString(xsltString, "application/xml");
const xsltProcessor = new XSLTProcessor();
xsltProcessor.importStylesheet(xsltDoc);
xsltProcessor.setParameter(null, "showItems", "yes");
xsltProcessor.setParameter(null, "highlightColor", "lightblue");
// Perform the transformation from XML to HTML
const resultFragment = xsltProcessor.transformToFragment(xmlDoc, document);
// Display the transformed result in the page
document.getElementById("result").appendChild(resultFragment);
結果
規範
| 規範 |
|---|
| DOM # dom-xsltprocessor-setparameter |
瀏覽器相容性
載入中…