在xsl中找到以下以下行:
var tdElem = document.getElementById('???') <!-- Would like to get td here, if possible -->
是否可以为包含td生成唯一ID并将其连接到我的javascript函数中?
xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td style="background-color: 'can_be_any_color_here'">
<xsl:value-of select="title"/>
<script>
var tdElem = document.getElementById('???') <!-- Would like to get td here, if possible -->
var bgColor = tdElem.style.backgroundColor;
var textColor = mycolorcontrastfx(bgcolor);
tdElem.style.color = textColor;
</script>
</td>
<td>
<xsl:value-of select="artist"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
xml
<?xml-stylesheet type="text/xsl" href="blackorwhite.xslt"?>
<catalog>
<cd>
<title>Empire Burlesque</title>
</cd>
<cd>
<title>Hide your heart</title>
</cd>
</catalog>
答案 0 :(得分:2)
您可以使用generate-id
为XML节点生成唯一ID
<xsl:variable name="id" select="concat('CDTableCell', generate-id())" />
或者,在这种特殊情况下,您只使用cd
所选的位置
<xsl:variable name="id" select="concat('CDTableCell', position())" />
要将ID分配给td
节点,您可以使用属性值模板
<td id="{$id}" style="..." />
试试这个XSLT
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<head>
<script>
function mycolorcontrastfx(bgColor)
{
return '#000000';
}
</script>
</head>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<xsl:variable name="id" select="concat('CDTableCell', position())" />
<td id="{$id}" style="background-color:#FFFFFF">
<xsl:value-of select="title"/>
<script>
var tdElem = document.getElementById('<xsl:value-of select="$id" />')
var bgColor = tdElem.style.backgroundColor;
var textColor = mycolorcontrastfx(bgColor);
tdElem.style.color = textColor;
</script>
</td>
<td>
<xsl:value-of select="artist"/>
</td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>