Javascript用'替换单引号

时间:2017-05-02 22:09:52

标签: javascript html

我正在研究MVC项目,并通过ViewData将字符串传递给视图。该字符串有单引号,双引号和其他特殊字符(为了给出一些背景知识,我将store locator教程作为测试项目,但使用Razor而不是asp.net。)

一旦变量点击Javascript标签,特殊字符就会被解码为HTML。 例如:

storeList =  [{ title: 'Location # 12', position: new google.maps.LatLng(32.85914441, -96.9444170)},{ title: 'Location # 7', position: new google.maps.LatLng(32.855526, -96.9555080)}]....

何时应包含:

storeList =  [{ title: 'Location # 12', position: new google.maps.LatLng(32.85914441, -96.9444170)},{ title: 'Location # 7', position: new google.maps.LatLng(32.855526, -96.9555080)}] ....

我尝试了this question上列出的解决方案但未成功:

<script type="text/javascript">
var storeList = $("<div/>").html(@ViewData["storeList"]).text();

但无论如何我都会收到错误:

"Uncaught SyntaxError: Unexpected token &" 

错误始于&amp;#39:

var storeList = $("<div/>").html([{ title: &#39;Location # 12&#39;, position: .....

非常感谢任何帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

使用@Html.Raw跳过使用Razor的html转义。

答案 1 :(得分:1)

尝试Html.Raw()插入未转义的html。