使用 HTML 实体了解 jquery text() 的细节
Understanding the specifics of the jquery text() with HTML Entities
我无法理解 jquery text()
函数结合 HTML 实体的具体情况。似乎是 text()
函数将特殊 HTML 实体转换回普通字符。特别是,我不确定这段代码的行为方式:
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
因为输出似乎是一个字符串,其中 HTML 实体未转义。这是否意味着 text()
函数转义 HTML 实体?
EDIT/FOLLOW 向上:
因为 text()
似乎只有 return 真实的文本内容,所以我很难理解这个 return 未转义的代码片段。如果 text()
return 是转义字符串,为什么 html
函数 return 是一个格式化字符串?
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
$("#test").html(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
如果您查看源代码,您会发现它正在从元素中提取 textContent。
https://j11y.io/jquery/#v=git&fn=jQuery.fn.text
textContent 是什么的一些文档:
https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
//https://j11y.io/jquery/#v=git&fn=jQuery.fn.text
console.log($("#test").get(0).textContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
text()
没有做任何特别的事情。浏览器本身在解析原始 HTML 时将实体转换为其呈现的字符。因此,当您在 HTML 中写入 <h1>
时,浏览器会将其转换为文字字符串 <h1>
。 .text()
只需 returns 这段文字。
当您随后使用 .html()
时,这会导致字符串被解析为 HTML,因此 <h1>
呈现为 HTML 标记,并且您得到格式化结果。
我无法理解 jquery text()
函数结合 HTML 实体的具体情况。似乎是 text()
函数将特殊 HTML 实体转换回普通字符。特别是,我不确定这段代码的行为方式:
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
因为输出似乎是一个字符串,其中 HTML 实体未转义。这是否意味着 text()
函数转义 HTML 实体?
EDIT/FOLLOW 向上:
因为 text()
似乎只有 return 真实的文本内容,所以我很难理解这个 return 未转义的代码片段。如果 text()
return 是转义字符串,为什么 html
函数 return 是一个格式化字符串?
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
$("#test").html(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
如果您查看源代码,您会发现它正在从元素中提取 textContent。 https://j11y.io/jquery/#v=git&fn=jQuery.fn.text
textContent 是什么的一些文档: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent
$(document).ready(function() {
var value = $("#test").text();
console.log(value);
//https://j11y.io/jquery/#v=git&fn=jQuery.fn.text
console.log($("#test").get(0).textContent);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<h1> test </h1>
</div>
text()
没有做任何特别的事情。浏览器本身在解析原始 HTML 时将实体转换为其呈现的字符。因此,当您在 HTML 中写入 <h1>
时,浏览器会将其转换为文字字符串 <h1>
。 .text()
只需 returns 这段文字。
当您随后使用 .html()
时,这会导致字符串被解析为 HTML,因此 <h1>
呈现为 HTML 标记,并且您得到格式化结果。