javascript - 为什么使用 .html() 会破坏这个 Replace 表达式?

标签 javascript jquery html regex

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

如果我在字符串上调用 .replace() 并使用 .text() 将结果设置为 div,则替换函数会按预期工作。

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

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

	$('#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 
<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>

我发现使用 .text() 而不是 .html() 可以解决问题,但是...

为什么会这样?

最佳答案

替换工作正常。

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

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

¤ 字符的 HTML 实体是 ¤,但浏览器也接受不带分号的 ¤ 形式。

关于javascript - 为什么使用 .html() 会破坏这个 Replace 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32291734/

相关文章:

javascript - jQuery Ajax - 不在循环内工作

javascript - Twitter Bootstrap 3 - 下拉菜单中的导航栏右侧问题

javascript - Onclick 未在对象上触发

html - Div 从容器中溢出

javascript - 将 html 中的表单值分配给 javascript 变量

javascript - 获取点击行的id

javascript - appendChild 在 IE 中无法正常工作

javascript - SailsJS : Requiring Assets, 例如 sails.io.js

javascript - 不使用 data-id 标签的 Jquery 菜单

javascript - 在使用 jQuery 创建的元素上使用 jQuery