2011-05-29 49 views
9

我正在嘗試將xsl變量值傳遞給javascript函數。如何將xsl變量值傳遞給javascript函數

我的XSL變量

<xsl:variable name="title" select="TITLE" /> 

我傳遞的價值這樣

<input type="button" value="view" onclick="javascript:openPage('review.html?review=$title')" /> 

我曾嘗試在不同的可能的方式上面的代碼,但我得到的錯誤。

<script type="text/javascript"> 
        function jsV() { 
        var jsVar = '<xsl:value-of select="TITLE"/>'; 
        return jsVar; 
        } 
       </script> 

       <input type="button" value="view" onclick="javascript:openPage('javascript:jsV()')" /> 

I also tried 

<input type="button" value="view" onclick="javascript:openPage('review.html?review='\'' 
    +$title+'\')" /> 

有沒有其他的方法,或者我不是做對了嗎?

+3

你是不是「XSLT變量的值傳遞給Javascript功能」。 XSLT沒有調用Javascript。它使用嵌入式Javascript生成HTML。你需要了解這個處理模型! – 2011-05-29 21:03:11

+0

明白了。非常感謝你。我不確定是否有可能改變問題的標題,但願我能。 – Govnah 2011-05-30 20:11:51

回答

4

你忘了{}:

<input type="button" value="view" onclick="javascript:openPage('review.html?review={$title}')" /> 
+1

它不顯示任何值。大括號內的任何內容都不會出現。 – Govnah 2011-05-29 11:12:51

+0

非常感謝你..工作正常!...在我測試你的代碼之前,我正在玩變量。我做了一些改變,我忘了它,這就是爲什麼它不工作。 – Govnah 2011-05-29 15:51:40

4

這裏是一個工作示例如何做到這一點:

這種轉變:

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
<xsl:output omit-xml-declaration="yes" indent="yes"/> 
<xsl:strip-space elements="*"/> 

<xsl:template match="/*"> 
    <xsl:variable name="vTitle" select="TITLE"/> 

    <input type="button" value="view" 
    onclick="javascript:openPage('review.html?review={$vTitle}')" /> 
</xsl:template> 

</xsl:stylesheet> 

當這個XML文檔的應用(沒有提供XML文件!):

<contents> 
<TITLE>I am a title</TITLE> 
</contents> 

產生想要的,正確的結果

<input type="button" value="view" 
onclick="javascript:openPage('review.html?review=I am a title')"/> 

說明:使用AVT(屬性值模板)。

+0

非常感謝你的例子。幫了很多忙。 – Govnah 2011-05-29 15:54:28

+0

@Govnah:不客氣。 – 2011-05-29 16:39:16

2

也可以通過做從JavaScript代碼訪問XSL變量在同一個文件中的以下內容:

<xsl:variable name="title" select="TITLE"/>

<script type="text/javascript"> 
    function getTitle() { 
     var title = <xsl:value-of select="$title"/>; 
     return title; 
    } 
</script> 
相關問題