在处理一个项目时,我遇到了一个错误并发现了这种意外行为:
如果我在字符串上调用 .replace()
并使用 .text()
将结果设置为 div,则替换函数会按预期工作。
但是,如果我在字符串上调用 .replace()
并使用 .html()
将结果设置为 div,则目标文本不会被替换字符串。
这是我的意思的一个例子:
$('#result1').text('¤cyId'.replace('¤cyId','¤cyId')); // works
$('#result2').html('¤cyId'.replace('¤cyId','¤cyId')); // doesnt work
var result = '¤cyId'.replace('¤cyId','¤cyId')
$('#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 具有相同的效果("¤cyId")
.
¤
字符的 HTML 实体是 ¤
,但浏览器也接受不带分号的 ¤
形式。
关于javascript - 为什么使用 .html() 会破坏这个 Replace 表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32291734/