如何将字符串存储在具有单引号和双引号的JavaScript变量中? [英] How to store a string in a JavaScript variable that has Single Quotes and Double Quotes?
问题描述
我需要创建一个存储动态生成的HTML内容的变量。从PHP返回的字符串中的html内容可能有单引号或双引号。
I need to create a variable storing dynamically generated HTML content. The html content in the String returned from PHP might have single or double quotes.
html_content=<?=$string;?>;
该字符串可能有双引号,如下所示:
The string may have double quotes like this:
<span id="something">something else</span>
或单引号如下:
<span id='something'>something else</span>
那么,我怎样才能在javascript中正确保存字符串?我不能使用单引号或双引号。
Then, how can I correctly save the string in javascript? I can't use single quotes or double quotes.
推荐答案
您可以通过在服务器端修改它来保存这种字符串在输出之前,如下所示:
You could save that kind of string by modifying it on the server side before output, like this:
html_content = "<?=addslashes($string);?>"
方法 addslashes($ string)
将然后在运行时将任何双引号转义为JavaScript变量。
The method addslashes($string)
would then escape any double quotes at runtime before feeding it to the JavaScript variable.
这篇关于如何将字符串存储在具有单引号和双引号的JavaScript变量中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!