如何将 xsl 变量值传递给 javascript 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6166994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 20:31:35  来源:igfitidea点击:

how to pass a xsl variable value to a javascript function

javascriptxslt

提问by Govnah

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

我正在尝试将一个 xsl 变量值传递给一个 javascript 函数。

My xsl variable

我的 xsl 变量

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

有没有其他方法,还是我做得不对?

采纳答案by sergzach

You forgot about {}:

您忘记了 {}:

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

回答by Dimitre Novatchev

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!):

应用于此 XML 文档时(未提供 XML 文档!):

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

说明:使用AVT(属性值模板)。

回答by Ilya Patrikeev

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

也可以通过执行以下操作从同一文件中的 JavaScript 代码访问 xsl 变量:

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

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

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