猿问

获取 HTML 并更改文档正文

请不要将此标记为重复项。我尝试了一切我能做的,但这是行不通的。我有 JavaScript 经验。这不是我第一次使用它


索引.html:


<!DOCTYPE html>

<html>

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <title>JUST_LOAD_ALREADY</title>

    <!-- <script defer src="/index.js"></script> -->

  </head>

  <body>

    PLEASSDETY FGUIRWFVUI

    <script>

      function loadContent() {

        fetch("/content.html")

          .then((res) => res.text())

          .then((text) => (document.body.innerHTML = text));

      }

      loadContent()

    </script>

  </body>

</html>

内容.html:


<h1>Content page</h1>

加载所有内容后正文中的预期页面内容: <h1>Content</h1>


body 内的实际页面内容: PLEAS


这既不是我的沮丧文字,也不是content.html我的内容。这真是要了我的命,请帮助告诉我为什么会发生这种情况。这是我仅有的两个文件 + 用于运行 Sirv 的 package.json


绝地无双
浏览 127回答 2
2回答

BIG阳

添加带有 id 的 div 并更改它innerHTML似乎有效,可能会“自杀”,因为像 @MarkusZeller 所说的那样,脚本位于体内。下面的代码有效:<!DOCTYPE html><html>&nbsp; <head>&nbsp; &nbsp; <meta charset="UTF-8" />&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0" />&nbsp; &nbsp; <title>JUST_LOAD</title>&nbsp; &nbsp; <!-- <script defer src="/index.js"></script> -->&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; PLEASSDETY FGUIRWFVUI&nbsp; &nbsp; <main id="content"></main>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; function loadContent() {&nbsp; &nbsp; &nbsp; &nbsp; fetch("/content.html")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then((res) => res.text())&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .then((text) => (document.getElementById("content").innerHTML = text));&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; loadContent();&nbsp; &nbsp; </script>&nbsp; </body></html>

哔哔one

或者把它放在头部window.addEventListener("load",() => {&nbsp;&nbsp; fetch("/content.html")&nbsp; &nbsp; .then(res => res.text())&nbsp; &nbsp; .then(text => document.body.innerHTML = text);})
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答