[英]Programmatically replacing `innerHTML` of whole document doesn't trigger loading 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 指定使用innerHTML
插入的<script>
标记不应执行。
我该如何解决这个问题?
我首先建议您通过寻找一种替代方法来更新您的文档来解决这个问题。 由于用户操作而重置整个 HTML 文档可能会导致许多问题; 我怀疑这个脚本问题将是您发现的最后一个意外副作用。
如果您绝对必须使用此方法,请参阅此问题以获取有关如何使其工作的一些想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.