在js函数调用中嵌入一个select值

XSL, embed a value-of select within a js function call

本文关键字:一个 select 函数调用 js      更新时间:2023-09-26

我有以下XSL代码(该格式为HTML创建了一个表)。表中的最后一列有一个按钮,该按钮有一个与之关联的onclick事件。

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" indent="yes" version="4.0"/>
<xsl:template match="/">
<table border="1" id="table1" align="center">
<tr><th>Item Number</th>
<th>Item Name</th>
<th>Description</th>
<th>Price</th>
<th>Quantity</th>
<th>Add</th></tr> 
<xsl:for-each select="/Items/Item">
<tr><td><xsl:value-of select="ItemID"/></td>
<td><xsl:value-of select="ItemName"/></td>
<td><xsl:value-of select="ItemDesc"/></td>
<td><xsl:value-of select="ItemPrice"/></td>
<td><xsl:value-of select="ItemQty"/></td>
<td><button onclick="addtoCart(15001)">Add to Cart</button></td> 
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>

我要做的是替换数字15001,与ItemID…所以代码可能是这样的-但我不确定它应该如何构造。

<td><button onclick="addtoCart(<xsl:value-of select="ItemID">)">Add to Cart</button></td>

哦…这里是javascript代码,它将调用…

function addtoCart(items)
{
   alert(items);
}

当前(传递值'15001')代码按预期工作。我知道我可以实现我想做的纯粹在Javascript(通过迭代表,看看哪个按钮被按下),但我的想法传递ItemID内的'addtoCart'函数似乎会干净得多…,好优雅。

你可以在这里使用属性值模板。

试试这个:

<button onclick="addtoCart({ItemID})">Add to Cart</button>

属性中的花括号表示要计算的表达式,而不是按字面意思输出。

注意:您也可以使用xsl:attribute来创建属性,但正如您所看到的,属性值模板要简单得多

<button>
   <xsl:attribute name="onclick">
       <xsl:value-of select="concat('addtoCart(', ItemID, ')')" />
   </xsl:attribute>
   Add to Cart
</button>