Escaping/Unescaping html in javascript?

Escaping/Unescaping html in javascript?

本文关键字:javascript in html Unescaping Escaping      更新时间:2023-09-26

在stackoverflow上有很多关于从js转义/取消转义html的回答问题。但我发现很难理解,因为它不太适合我的上下文。我有一个变量"消息",其中包含以下字符串:

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

我使用"this.message"在js文件中显示此消息。而不是看到超链接的"Google",我可以从字面上看到整个字符串:

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

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

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

如何获得超链接的谷歌?我必须逃跑/逃脱吗?如何?

显示消息的代码:

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

在 django 模板中添加 html 格式,如下所示:

{% 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 %}

或者你可以在客户端javascript中添加html格式,如下所示:

$.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);
        });