【发布时间】:2021-12-13 18:14:13
【问题描述】:
我正在尝试使用innerHTML 渲染一些img 元素,在某些情况下它可以工作,而在其他情况下则不行。
sn-p:
我有两个字符串,在视觉上它们具有相同的内容,但是严格相等比较 (===) 并没有说同样的话。
可能是编码问题?有没有什么办法可以转义字符串来解决问题?
const html = '<h2>HTML:</h2><p>First Image:</p> <img src="https://images.pexels.com/photos/8971740/pexels-photo-8971740.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Test" width="150" height="150"/> <p>Second Image: </p> <img src="https://images.pexels.com/photos/8971740/pexels-photo-8971740.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Test" width="150" height="150"/>';
const htmlAux = '<h2>HTML:</h2><p>First Image:</p> <img src="https://images.pexels.com/photos/8971740/pexels-photo-8971740.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Test" width="150" height="150"/> <p>Second Image: </p> <img src="https://images.pexels.com/photos/8971740/pexels-photo-8971740.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Test" width="150" height="150"/>';
const div = document.getElementById("div-test");
div.innerHTML = html + htmlAux;
console.log('html == htmlAux: ', html == htmlAux)
console.log('typeof(html): ', typeof(html));
console.log('typeof(htmlAux): ', typeof(htmlAux));
<div id="div-test"></div>
【问题讨论】:
-
</img src="http:>为什么在你的 innerHTML 内容的末尾?看起来这可能是问题...我想您在服务器端的循环可能会迭代太多次...例如:如果您有一个包含 2 个图像的 3 条目数组并且最后一个条目是空的。 ..并且您的代码没有进行一些条件测试...循环可能会尝试输出空字符串...但是它不能解释为什么您似乎试图用 关闭标记这是不正确的...
正在自动关闭... 例如:
<img src="http://where.com" /> -
@aequalsb 我相信这是因为在设置内部 HTML 之后,斜杠被从字符串中删除了......即使标签正确关闭,错误仍然存在:/
-
测试了您的代码,它可以正常工作。见jsfiddle.net/76xcyaoq
-
@lukas.j 感谢帮助,但尝试复制问题 sn-p 来回答并查看
console.log,idk 是什么原因造成的,它看起来像编码问题 -
jsfiddle上有一个控制台(右下角)。我没有看到你描述的问题。
标签: javascript innerhtml