为什么在字符串末尾的实体转义不会出现在domready上的document.write(x)?

问题描述 投票:3回答:2

var target = '<p><img alt=\"\" src=\"upfiles\/54591303758197437.jpg\" \/><\/p>'
$(function(){
    var x=$('<div/>').text(target).html();
    alert(x);
    document.write(x)
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I show the escaped string contained html tags and write in webpage.
The escaped string in the alert window is right, but after closing the alert window you can ony see (screenshot):
<p><img alt="" src="upfiles/54591303758197437.jpg" /></p

最后的>在哪里?

为什么<p><img alt="" src="upfiles/54591303758197437.jpg" /></p>不会出现在网页上?

javascript jquery document.write html-escape-characters
2个回答
3
投票

我在Chrome 69(Windows)上遇到了相同的症状。

根据document.close()的建议,通过添加MDN调用来管理修复它:

target = '<p><img alt=\"\" src=\"upfiles\/54591303758197437.jpg\" \/><\/p>'
$(function(){
    x=$('<div/>').text(target).html();
    alert(x);
    document.write(x);
    document.close();
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

0
投票

对这个令人困惑的难题的正确和正式记录的答案是在@PeterB's response。对于任何寻求快速修复的人来说,只需在字符串的末尾附加一个空格,然后你就恢复了理智。

document.write(x+' ')
© www.soinside.com 2019 - 2024. All rights reserved.