Javascript variable = xsl value-of

Javascript variable = xsl value-of

本文关键字:value-of xsl variable Javascript      更新时间:2023-09-26

我使用的是这样的JavaScript:

<script>
  <xsl:for-each select = '/request/alldata'>
    var l_allDataValue   = '<xsl:value-of select="." />';
    var l_dataArray = l_allDataValue.split('!~');
    callFunction(l_dataArray);
  </xsl:for-each>
</script>

但是如果在/request/alldata中有一个撇号',它将破坏JavaScript,因为下面的表达式包含在撇号中:

'<xsl:value-of select="." />'

但是如果我用以下任何一个替换它,它就可以工作了…

"<xsl:value-of select="." />" OR "<xsl:value-of select='.' />"

现在我知道撇号'与JavaScript代码冲突,但哪种解决方案将在所有浏览器中工作?

您可以使用'<xsl:value-of select="." />',但是您需要通过在<alldata>前面加上斜杠来转义''

您可以使用"<xsl:value-of select="." />" or "<xsl:value-of select='.' />",但如果<alldata>有可能包含双引号,那么您也需要转义,如'"

如果你想使用第一个,那么这将转义单引号:

<xsl:template name="escapeSingleQuotes">
  <xsl:param name="txt"/>
  <xsl:variable name="backSlashSingleQuote">&#92;&#39;</xsl:variable>
  <xsl:variable name="singleQuote">&#39;</xsl:variable>
  <xsl:choose>
    <xsl:when test="string-length($txt) = 0">
      <!-- empty string - do nothing -->
    </xsl:when>
    <xsl:when test="contains($txt, $singleQuote)">
      <xsl:value-of disable-output-escaping="yes" 
                    select="concat(substring-before($txt, $singleQuote), $backSlashSingleQuote)"/>
      <xsl:call-template name="escapeSingleQuotes">
        <xsl:with-param name="txt" select="substring-after($txt, $singleQuote)"/>
      </xsl:call-template>
    </xsl:when>
    <xsl:otherwise>
      <xsl:value-of disable-output-escaping="yes" select="$txt"/>
    </xsl:otherwise>
  </xsl:choose>
</xsl:template>

你可以在你的代码中这样使用:

var l_allDataValue = '<xsl:call-template name="escapeSingleQuotes">
                        <xsl:with-param name="txt" select="."/>
                      </xsl:call-template>'