转义在onclick事件中传递给js函数的字符串中的可能引号 [英] escape possible quotes in string passed to a js function in a onclick event

查看:385
本文介绍了转义在onclick事件中传递给js函数的字符串中的可能引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在jspx中有以下循环:

I have the following cycle in a jspx:

<c:forEach var="var" items="${dataFile.list.rows}">
  <li>
    <div>
      <a href="#" onClick="myFunct('${var.url}','escape(${var.title}),'escape(${var.descr})');">
        <img width="108" height="66" alt="" src="${var.img}" />
      </a>
    </div>
  </li>
</c:forEach>

函数myFunct自己执行一些操作.当${var.title}${var.descr}包含引号或双引号时,就会出现我的问题.我无法事先知道会不会有一些.

Where function myFunct does some stuff on its own. My problems arise when either ${var.title} or ${var.descr} contain quotes or double quotes. I can't know in advance whether there's going to be some or which.

我尝试了以上内容,我在元素之前尝试了一个辅助js部分,但不知道要使用哪种引号,所以我无法猜测是否需要放置escape("${var.title}");escape('${var.title}');

I tried the above, I tried a little helper js section just before the element, but not knowing which kind of quotes I'm going to have I can't guess whether I need to put escape("${var.title}"); or escape('${var.title}');.

关于如何解决此问题的任何想法?谢谢.

Any idea on how to solve this? Thanks.

推荐答案

您应该在服务器端而不是在客户端执行此操作.无论如何,在客户端进行此操作为时已晚.根据值的唯一目的,是将其用作HTML的一部分且不包含换行符,还是用作JS代码,您可以使用JSTL提供的EL函数fn:escapeXml()

You should do it in the server side, not in the client side. Doing it in the client side is too late anyway. Depending on the sole purpose of the value, whether it's going to be used as part of HTML and doesn't contain linebreaks, or as JS code, you can use either the JSTL-provided EL function fn:escapeXml()

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<a onclick="myFunct('${var.url}','${fn:escapeXml(var.title)}','${fn:escapeXml(var.descr)}');">

或创建一个使用Apache Commons Lang

or create a custom EL function which uses Apache Commons Lang StringEscapeUtils#escapeJavaScript() under the covers.

<%@taglib prefix="my" uri="http://example.com/functions" %>
...
<a onclick="myFunct('${var.url}','${my:escapeJs(var.title)}','${my:escapeJs(var.descr)}');">

您可以在这个答案.

我猜想它将被用作HTML的一部分,因此fn:escapeXml()就足够了.

I guess that it's going to be used as part of HTML, so fn:escapeXml() could to be sufficient.

这篇关于转义在onclick事件中传递给js函数的字符串中的可能引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆