使用 jQuery 转义 HTML 字符串 [英] Escaping HTML strings with jQuery
本文介绍了使用 jQuery 转义 HTML 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有谁知道在 jQuery 中从字符串中转义 HTML 的简单方法吗?我需要能够传递任意字符串并将其正确转义以在 HTML 页面中显示(防止 JavaScript/HTML 注入攻击).我确信可以扩展 jQuery 来做到这一点,但我目前对框架的了解还不够多.
解决方案
由于您正在使用 jQuery,您可以只需设置元素的 text
属性:
//之前://<div class="someClass">text</div>var someHtmlString = "<script>alert('hi!');</script>";//设置一个 DIV 的文本:$("div.someClass").text(someHtmlString);//后://<div class="someClass"><script>alert('hi!');</script></div>//获取字符串中的文本:var 转义 = $("").text(someHtmlString).html();//价值://<script>alert('hi!');</script>Does anyone know of an easy way to escape HTML from strings in jQuery? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.
解决方案 Since you're using jQuery, you can just set the element's text
property:
// before:
// <div class="someClass">text</div>
var someHtmlString = "<script>alert('hi!');</script>";
// set a DIV's text:
$("div.someClass").text(someHtmlString);
// after:
// <div class="someClass"><script>alert('hi!');</script></div>
// get the text in a string:
var escaped = $("<div>").text(someHtmlString).html();
// value:
// <script>alert('hi!');</script>
这篇关于使用 jQuery 转义 HTML 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文