how to pass a xsl variable value to a javascript f

2019-03-13 08:06发布

问题:

i am trying to pass an xsl variable value to a javascript function.

My xsl variable

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

i'm passing the value like this

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

i have tried the above code in different possible ways but i gets errors.

<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+'\')" />

Is there alternative way or am i not doing it right?

回答1:

You forgot about {}:

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


回答2:

Here is a working example how to do this:

This transformation:

<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>

when applied on this XML document (no XML document was provided!):

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

produces the wanted, correct result:

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

Explanation: Use of AVT (Attribute Value Templates).



回答3:

It is also possible to access xsl variable from a JavaScript code in the same file by doing the following:

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

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