2015-03-13 67 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