为什么使用.html()会破坏这个替换表达式?

Del*_*D0D 6 html javascript regex jquery

在处理项目时,我遇到了一个错误并发现了这种意外行为:

如果我调用.replace()一个字符串并使用.text()replace函数将结果设置为div ,就像我期望的那样工作.

但是,如果我调用.replace()字符串并将结果设置为div .html(),则不会在字符串中替换目标文本.

这是我的意思的一个例子:

	$('#result1').text('¤cyId'.replace('¤cyId','&currencyId')); // works
	$('#result2').html('¤cyId'.replace('¤cyId','&currencyId')); // doesnt work 

    var result = '¤cyId'.replace('¤cyId','&currencyId')
	$('#result3').text(result); // works
	$('#result4').html(result); // doesnt work 
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result1"></div><br>
<div id="result2"></div><br>
<div id="result3"></div><br>
<div id="result4"></div>
Run Code Online (Sandbox Code Playgroud)

我看到使用.text()而不是.html()解决问题,但......

为什么会这样?

Guf*_*ffa 6

替换工作正常.

当您使用该html方法时,它看起来只是错误的字符串在元素中结束,因为&curren¤被浏览器解码,因此&currencyId显示为¤cyId.

当您使用该text方法时,文本不会被解码为HTML代码,因此.text("&currencyId")具有相同的效果.html("&amp;currencyId").

¤角色的HTML实体是&curren;,但浏览器也接受&curren没有分号的表单.