我必须使用innerHTML将包含内联事件处理程序的一串html代码注入到元素中。像这样的东西:
document.getElementById('some-div')
.innerHTML = '<button onclick="alert(\'<html>\');"><html></button>';
我希望得到这个结果:
<button onclick="alert('<html>');"><html></button>';
但实际的DOM看起来像这样:
<button onclick="alert('<html>');"><html></button>';
为什么内联事件处理程序部分会被浏览器自动转义?没有双重逃避可以防止这种情况吗?
当您通过设置Element.innerHTML将HTML数据传递到浏览器时,浏览器必须解释/解析HTML以呈现它。即使它没有专门呈现onclick属性,它仍然必须解析编码。正如Chris Barr所说,你必须重新编码字符串,这样当浏览器解析它时,它将解析为正确的版本。
使用像https://opinionatedgeek.com/codecs/htmlencoder这样的简单HTML编码器,您可以重新编码字符串,它应该返回“<html>”。