【问题标题】:easy way to escape html using jquery in ie 8在 ie 8 中使用 jquery 转义 html 的简单方法
【发布时间】:2013-02-13 02:44:20
【问题描述】:

我想将"x < y" 等文本转换为正确转义的"x < y"。我一直在使用浏览器内置的转义功能来做到这一点:

 div = $('<div></div>');
 div.text(my_text);
 escaped_text = div.html();

这很好用....直到我在 IE 8 中进行测试,当您调用 .html() 时它会吃掉换行符。是否有类似的简洁、健壮的方式在 IE 8 中也可以使用?

【问题讨论】:

  • 不确定您是否能够/想要添加一个库,但 underscore 效果很好。
  • @PaulHoenecke 谢谢,如果我找不到更好的解决方案,这将是我的后备方案。随意发布它作为答案...

标签: javascript jquery internet-explorer-8 innerhtml


【解决方案1】:

Underscore 有 escape/unescape 方法。这是一个非常有用的库。

【讨论】:

  • Underscore 的转义对换行没有任何作用,但您可以像这样手动处理它们:escaped_text = _.escape(my_text).replace(/\n/g, '&lt;br/&gt;'); - 对此进行了测试,它似乎等同于我在现代浏览器中的原始代码,并且有效正确地在 IE 8 中。
【解决方案2】:

您可以像这样将 html() 方法换成 innerHTML 属性:

div = $('<div></div>');
div.text(my_text);
escaped_text = div[0].innerHTML;

【讨论】:

  • 刚刚在 IE 8 中尝试过,它看起来好像 innerHTML 返回的内容与 html() 一样?
【解决方案3】:

你可以试试这个:

jQuery 代码:

(function ($) {
    $.fn.escapeHtml = function () {
        var e = document.createElement("DIV"),
            s = '';
        e.innerHTML = $(this).val();
        s = e.textContent || e.innerText || "";
        e.remove();
        return s.replace(/<\/?([a-z][a-z0-9]*)\b[^>]*>?/gi, '');
    }
})(jQuery);

如何使用:

// if you want to real input value then, go with jQuery '.val()' option
var htmlString = $('#yourelement').val();

// remove html character, go with jQuery '.escapeHtml()' option
var safeHtmlString = $('#yourelement').escapeHtml();

或者你可以作为 jQuery 插件使用:

jQuery.escapeHtml()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    • 2010-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    相关资源
    最近更新 更多