[英]jQuery.html() with single quotes
I can't figure out how to write this so it works. 我无法弄清楚如何写这个,所以它的工作原理。 We have a page where users can upload documents and the list will show on the screen.
我们有一个页面,用户可以上传文档,列表将显示在屏幕上。 The problem comes when the filename has a single quote in it.
当文件名中包含单引号时,就会出现问题。 We are using jQuery.
我们正在使用jQuery。 There's some code generation going on but this is the basics of what comes out.
有一些代码生成正在进行,但这是出来的基础知识。
$(someElement).html('<label onclick="$(someOtherElement).attr(\'title\', \'TheFile\\'Name.pdf\')">Some Text</label>');
The single quote in the file name is causing a problem. 文件名中的单引号导致问题。 I've tried escaping it both with one backslash and 2 backslashes.
我试过用一个反斜杠和两个反斜杠来逃避它。 With a single backslash the code runs but produces this html:
使用单个反斜杠代码运行但生成此html:
<label onclick="$(someOtherElement).attr('title', 'TheFile'Name.pdf')">Some Text</label>
which now fails on the onclick. 现在在onclick失败了。
With 2 backslashes, the jquery html()
line won't run at all. 使用2个反斜杠,jquery
html()
行根本不会运行。 In both cases I get Unexpected identifier, just at different points. 在这两种情况下,我都会在不同的点获得意外的标识符。
You need a tripple backslash : 你需要一个三重反斜杠:
$(someElement).html('<label onclick="$(someOtherElement).attr(\'title\', \'TheFile\\\'Name.pdf\')">Some Text</label>');
Why 3? 为什么3?
The first one escape the second backslash that will escape the '
in the HTML code . 第一个逃避第二个反斜杠,它将逃脱HTML代码中的
'
。
The third one escape the '
to prevent the string from closing. 第三个逃脱
'
以防止字符串关闭。
You need to not just double but triple the backslashes. 你不仅需要加倍,而且还需要三倍的反斜杠。
The reason is that you initially escape the '
by doing \\'
. 原因是你最初逃脱
'
做\\'
。 Now however you have two characters to escape so \\
goes to \\\\
and '
goes to \\'
again giving \\\\\\'
. 但是现在你有两个字符逃脱这样
\\
去\\\\
和'
去\\'
再次给\\\\\\'
。
How to escape single quote 如何逃避单引号
Try using the character values with the & symbol to escape quotes. 尝试使用带有&符号的字符值来转义引号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.