2015-03-13 68 views
0

关于从js转义/转义html的stackoverflow有很多回答问题。但是我发现很难理解,因为它不适合我的上下文。我有有这个字符串变量“消息”:在javascript中转义/转义html?

message="<a href="www.google.com">Google</a>" 

我的js文件使用“this.message”显示此消息。相反,看到超链接的“谷歌”,我可以从字面上看到整个字符串:

<a href="www.google.com">Google</a> 

如果我检查元素,我可以看到,这个字符串被翻译成:

&lt;a href="www.google.com"&gt;Google;&lt;&gt 

我如何获得超链接谷歌?我必须逃脱/ unescape?怎么样?

代码以显示消息:

$.each(mdn.notifications || [], function() { 
      $('<div class="notification">' + this.message + '</div>')[insertLocation.method](insertLocation.selector); 
     }); 
+0

在您的“消息”任务中,您在双引号内显示​​双引号。这是一个错字吗?另外,显示消息的代码是什么? – HeadCode 2015-03-14 17:10:39

+0

糟糕。请考虑“消息”只是一个例子。在浏览器检查元素<显示为<我只是想阻止,以便我的html得到正确渲染。同时检查编辑的问题。 – abhidoeslinux 2015-03-14 17:18:33

+0

这里有很多我不明白你的JQuery语法,但你可以试试这个:var msg = $ .parseHTML(this.message),然后在你的JQuery函数中使用msg。 – HeadCode 2015-03-14 18:00:11

回答

0

添加HTML格式的Django模板是这样的:

{% if messages %}notifications: [ 
       {% for message in messages %}{% if 'wiki_redirect' not in message.tags or waffle.flag('redirect_messages') %}{message: "<div class='my-message'>{{ message }}</div>", tags: "{{ message.tags }}", level: "{{ message|level_tag }}"}{% if not loop.last %},{% endif %}{% endif %} 
       {% endfor %} 
      ], 
      {% else %} 
      notifications: [], 
      {% endif %} 

或者,您可以添加HTML在客户端的JavaScript格式的这样的:

$.each(mdn.notifications || [], function() { 
      // Make it so 
      $('<div class="notification ' + this.level + ' ' + this.tags + '" data-level="' + this.level + '"><div class="my-message">' + this.message + '</div></div>')[insertLocation.method](insertLocation.selector); 
     }); 
+0

感谢您的回复!仍然得到相同的结果。在潜水标签内部,存在包含标签的纯文本。为什么标记邮件安全在这种情况下不起作用? – abhidoeslinux 2015-03-14 07:43:29

+0

即使使用了mark_safe,html也不会被转义? – abhidoeslinux 2015-03-14 15:23:41

+0

Nikos M:编辑问题 – abhidoeslinux 2015-03-14 17:07:13