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 |
浏览器兼容性
加载中…