为什么你不能通过连续调用 .text() JQuery 来逃避
why can't you escape with consecutive calls to .text() JQuery?
>我正在使用jQuery转义表单输入,如下所示
var escapedStr = $('<div>').text(formInput).html();
它工作得很好,很开心。
但是为什么以下方法不起作用呢?
var escapedStr = $('<div>').text(formInput).text();
如果是var formInput = '<h1>'
,那么$('<div>').text(formInput).text();
应该在div
中插入一个转义的h1
标签,然后抓取转义的文本本身?相反,第二个text()
获取一个 HTML 标记,该标记在添加到 DOM 时呈现。
这是怎么回事?有人可以解释一下吗?这是一个带有各种示例的JS小提琴。我对第二种情况感到困惑。https://jsfiddle.net/EmOnTheWeb/72sbypg7/9/
考虑此代码如何处理源文本<h1>am I rendering?
。
var escapedStr = $('<div>').text(formInput).html();
- 将
formInput
作为文本插入到div
:
这会产生:
<div><h1>am I rendering?</div>
- 获取
div
的 HTML 内容:
这会产生:
<h1>am I rendering?
如果将.html()
替换为 .text()
,这意味着"获取div 的文本内容"。因此,它应该等于您作为文本输入的内容。
<h1>am I rendering?
这似乎有点令人困惑,但这只是因为您的文本是 HTML。行为是正确的。也许这些方法的名称令人困惑。这是另一种思考它们的方式:
div.text() ~= htmlDecode(div.innerHTML)
div.text(str) ~= div.innerHTML = htmlEncode(str)
div.html() ~= div.innerHTML
div.html(str) ~= div.innerHTML = str
(注意,以上不是很准确,因为text()
实际上为您提供了元素及其所有子元素的级联文本节点,但对于只有文本而没有子元素的 HTML 元素来说是正确的)
在你的 JS Fiddle 示例中,第二个示例看起来只是转义失败,因为你使用的是 jQuery append()
方法。
jQuery DOM 操作方法需要整个 DOM 节点,因此当您调用 append()
时,它会自动插入结束</h1>
标记。
var str = '<h1>am I rendering?';
/*
text(str) calls document.createTextNode(str), which escapes the markup
html() gets the innerHTML property of the div which at this point is "<h1>hello"
*/
var attemptEsc = $('<div>').text(str).html();
$('body').append('1. insert with text() grab out with html() gives: ' +attemptEsc);
/*
text(str) calls document.createTextNode(str), which escapes the markup
text() gets the textContent property of the div, which at this point is "<h1>hello"
because textContent unescapes HTML entities
*/
var attemptEsc1 = $('<div>').text(str).text();
$('body').append('<br> 2. insert with text() grab out with text() gives: '+attemptEsc1);
/*
html(str) sets the innerHTML of the div, attempting to create complete DOM nodes
html() gets the innerHTML property of the div which at this point is "<h1>hello</h1>"
*/
var attemptEsc2 = $('<div>').html(str).text();
$('body').append('<br> 3. insert with html() grab out with text() gives: ' +attemptEsc2);
/*
html(str) sets the innerHTML of the div, attempting to create complete DOM nodes
text() gets the textContent property of the div, which at this point is "hello"
*/
var attemptEsc3 = $('<div>').html(str).html();
$('body').append('<br> 4. insert with html() grab out with html() gives: '+attemptEsc3);
相关文章:
- 无法从 jQuery RSS Feed 中的 localStorage 动态替换类
- 如何使用jQuery自动打开页面上的所有链接
- 如何使用jquery在填充自动完成的值后使文本框只读
- jQuery:循环一个具有不同超时值的循环
- 用程序搜索JQuery数据表中的文本
- 使用 jQuery 的 .on 函数如何获取事件的原始元素
- jQuery匹配JSON对象的部分文本
- Jquery POST未填充数组
- JQuery使计数器每次更改时都会增加
- 如何在Angular2中使用jQuery插件
- 提高JQuery的性能
- 无法在通过jQuery的ajax加载的页面中执行javascript
- JQuery合并了keyup和focusout两个函数
- 如何使用jQuery选择下拉列表的值
- 将PHP变量传递给jQuery时遇到问题
- jQuery UI自动完成突然停止工作
- 剑道网格jQuery动画()问题
- 如何使jQuery插件函数可调用以供独立使用,而不在集合上操作
- 为什么你不能通过连续调用 .text() JQuery 来逃避
- Javascript/jQuery正在逃避我的escape