javascript - 以编程方式替换整个文档的“innerHTML”不会触发加载 JS?
问题描述
我使用 JavaScript 在单击按钮时以编程方式替换整个页面:
btn.addEventListener("click", evt => {
fetch("hqsc").then(r => {
const txt = r.text();
txt.then(t => {
document.querySelector('html').innerHTML = t;
console.log(t);
});
}).catch(console.log);
});
打算加载的页面如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"></meta>
<style type="text/css">
body {
background-color: lightblue;
}
form#authenticate {
width: 30vw;
height: auto;
margin: 20vh auto;
border: 1px dashed black;
border-radius: 5px;
background-color: darkgray;
padding: 15px 10px;
display: grid;
grid-template-columns: 120px 100px;
grid-column-gap: 15px;
grid-row-gap: 20px;
grid-column-start: 1;
grid-row-start: 1;
}
</style>
**<script type="module" src="/static/auth.js"></script>**
</head>
<body>
<form id="authenticate">
<label for="username">User</label>
<input id="username" type="text" name="username" />
<label for="password">Pass</label>
<input id="password" type="password" name="password" />
<input type="submit" value="Enter" />
</form>
</body>
</html>
我注意到/static/auth.js
新页面上的 javascript 完全被忽略了。为什么会被忽略?我该如何解决这个问题?
解决方案
为什么会被忽略?
出于安全原因。请参阅https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations中的此评论:
HTML5 指定<script>
插入的标签innerHTML
不应该执行。
我该如何解决这个问题?
我首先建议您通过寻找一种替代方法来更新您的文档来解决这个问题。由于用户操作而重置整个 HTML 文档可能会导致许多问题;我怀疑这个脚本问题将是您发现的最后一个意外副作用。
如果您绝对必须使用此方法,请参阅此问题以获取有关如何使其工作的一些想法。
推荐阅读
- android - 如何使用 gson 在 Kotlin 的 Json 数组中插入 Json 对象
- javascript - 如何使用按钮创建 div 元素
- java - 为什么 myProcess.getInputStream() 可以使用 java.exe 而不是 javaw.exe?
- java - 无法运行对话框
- javascript - mongo 仅在每个元素都符合条件时才查找
- json - jq:如何通过从另一个对象读取的名称查找 JSON 对象?
- python - 'int' 对象不可迭代”当使用 itertools 并将函数应用于每一行时
- swift - 滚动视图内容偏移在 viewDidLoad 中无响应
- javascript - 如何通过分配 css 类来更改表格单元格边框颜色?
- javascript - Django -- 将字典传递给模板并绘制折线图