为什么你不能通过连续调用 .text() JQuery 来逃避

why can't you escape with consecutive calls to .text() JQuery?

本文关键字:JQuery 逃避 text 调用 不能 连续 为什么      更新时间:2023-09-26

>我正在使用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();
  1. formInput作为文本插入div

这会产生:

<div>&lt;h1&gt;am I rendering?</div>
  1. 获取divHTML 内容:

这会产生:

&lt;h1&gt;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 "&lt;h1&gt;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);