jQuery中的text()和html()函数有什么区别?
$("#div").html('<a href="example.html">Link</a><b>hello</b>');
vs
$("#div").text('<a href="example.html">Link</a><b>hello</b>');
jQuery中的text()和html()函数有什么区别?
$("#div").html('<a href="example.html">Link</a><b>hello</b>');
vs
$("#div").text('<a href="example.html">Link</a><b>hello</b>');
当前回答
我认为区别在于插入html标签 在text()中你的HTML标签没有函数
$('#output').html('You are registered'+'<br>' +' '
+ 'Mister'+' ' + name+' ' + sourname ); }
输出:
You are registered <br> Mister name sourname
用html()替换text()
输出
You are registered
Mister name sourname
那么标签<br>在html()中工作
其他回答
基本上,$("#div").html使用element。innerHTML设置内容,$(“#div”)。text(可能)使用element.textContent。
http://docs.jquery.com/Attributes/html:
Set the html contents of every matched element
http://docs.jquery.com/Attributes/text:
Similar to html(), but escapes HTML (replace "<" and ">" with their HTML
entities).
我认为区别在于插入html标签 在text()中你的HTML标签没有函数
$('#output').html('You are registered'+'<br>' +' '
+ 'Mister'+' ' + name+' ' + sourname ); }
输出:
You are registered <br> Mister name sourname
用html()替换text()
输出
You are registered
Mister name sourname
那么标签<br>在html()中工作
尽可能使用.text(),因为它会转义HTML,特别是如果您正在添加任何不受信任的数据,例如来自用户输入。. HTML()有一些xss漏洞
text()方法实体-转义传入它的任何HTML。当您想要插入对查看页面的人可见的HTML代码时,请使用text()。
从技术上讲,第二个示例生成:
<a href="example.html">Link</a><b>hello</b>
它将在浏览器中呈现为:
<a href="example.html">Link</a><b>hello</b>
您的第一个示例将呈现为一个实际的链接和一些粗体文本。
当您打算将值显示为简单文本时,请使用.text(…)。
当您打算将值显示为html格式的文本(或html内容)时,使用.html(…)。
当你不确定你的文本(例如来自输入控件)不包含在HTML中有特殊意义的字符/标记时,你一定要使用.text(…)。这是非常重要的,因为这可能会导致文本不能正常显示,但也可能导致不需要的JS脚本片段(例如来自另一个用户输入)被激活。