我刚刚注意到浏览器忽略了 HTML 格式(例如对齐此代码段中的两个属性):
<div id="container">
<div id="contained"
other-prop="some value">
</div>
</div>
如果你跑
var container = document.getElementById('container');
console.log(container.innerHTML);
你得到输出
<div id="contained" other-prop="some value">
</div>
无论它在源代码中是如何编写的,或者即使您直接在 JavaScript 中设置 .innerHTML 也没有关系。
是否可以查询用户在JS中写的某个元素对应的页面源?有空白和一切。当用户使用 DOM 操作修改元素时,我可以看到存在问题,在这种情况下,如果
- 所有未修改的内容都保留原始用户格式,或者
- 可以获取用户在页面加载时编写的原始源代码,无需 DOM 修改
一个片段,您可以看到它的实际效果:
var container = document.getElementById('container');
console.log(container.innerHTML);
container.innerHTML = `
<div id="contained"
other-prop="some value">
</div>
`;
console.log(container.innerHTML);
container.children[0].setAttribute('modification', '');
console.log(container.innerHTML);
<div id="container">
<div id="contained"
other-prop="some value">
</div>
</div>
最佳答案
根本不可能。 将代码视为计算机之间用于表达视觉表示的消息,其中空格并不重要。
关于javascript - .innerHTML 丢失 HTML 语法格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57630710/