简体   繁体   English

Function addEventListener 不适用于 Fetch

[英]Function addEventListener doesn't work with Fetch

What I am doing:我在做什么:
I am making a portfolio for me, using HTML, CSS and JavaScript pure.我正在为我制作一个投资组合,使用 HTML、CSS 和 JavaScript 纯。 I am creating projects page and trying create a <p> with JavaScript and inserting data from a.json file, but:我正在创建项目页面并尝试使用 JavaScript 创建一个<p>并从 a.json 文件中插入数据,但是:

What's the problem?有什么问题?
The Fetch API doesn't working with addEventListener. Fetch API 不适用于 addEventListener。

I had tried:我试过:
Create the <p> first and out of addEventListener function insert the data, but also doesn't work.先创建<p> ,然后从addEventListener function 中插入数据,还是不行。

Part of JavaScript: JavaScript 的一部分:

async setProjects(){
  let response = await fetch("contents/projects.json");
  let responseJson = await response.json();
    
  document.addEventListener("DOMContentLoaded", function () {
    var p = document.createElement('p');
    
    p.innerHTML = responseJson.one.bio;
    p.id = "bio-project";
    // p.style.cssText = 'border-left: 8px solid aqua;';
    
    document.querySelector(".projeto-contents").appendChild(p);
  }, false)
}

HTML: HTML:

<!DOCTYPE html>
<html lang="pt-br">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Projetos - Vitor Hugo's Portifolio</title>
    <link rel="stylesheet" href="../style.css" />
    <script type="text/javascript" src="script.js"></script>
  </head>

  <body>
    <header>
      <nav>
        <a class="logo" href="/">Vitor Hugo</a>
        <div class="mobile-menu">
          <div class="line-1"></div>
          <div class="line-2"></div>
          <div class="line-3"></div>
        </div>
        <ul class="nav-list">
          <li><a href="index.html">Home</a></li>
          <li><a href="sobre.html">Sobre</a></li>
          <li><a href="projetos.html">Projetos</a></li>
          <li><a href="contatos.html">Contato</a></li>
        </ul>
      </nav>
    </header>
    <script src="../mobile-screen.js"></script>

    <!--  -->
    <div class="projetos">
      <div class="projeto-contents">
        <h1 id="titulo-project">test</h1>
      </div>
    </div>
    <script language="javascript">
      const portifolio = new Portifolio();
      portifolio.setProjects();
    </script>
  </body>
</html>

JSON: JSON:

{
  "one":{
    "name":"Lorem",
    "bio":"Lorem ipsum dolor sit amet consectetur adipisicing elit. Eos dolore pariatur accusamus quaerat hic distinctio, cum, ratione dignissimos, doloremque incidunt provident deleniti consectetur qui alias quam quod porro error temporibus.",
    "language":"Python"
  },
  "two":{
    "name":"testname2",
    "bio":"testbio2",
    "language":"testlanguage2"
  },
  "three":{
    "name":"testname3",
    "bio":"testbio3",
    "language":"testlanguage3"
  },
  "four":{
    "name":"testname4",
    "bio":"testbio4",
    "language":"testlanguage4"
  }
}

Project link: https://github.com/vitorhugo1207/portfolio项目链接: https://github.com/vitorhugo1207/portfolio

What I have to do?我必须做什么? please help me.请帮我。 And one more thing: about json is possible to use number as index?还有一件事:关于 json 是否可以使用数字作为索引? And sorry for any error orthography and grammar I am studing English.对于我正在学习英语的任何拼写和语法错误,我深表歉意。

async/await allows you to write code that looks like it's synchronous, but it isn't really -- it's just syntactic sugar for working with promises. async/await允许您编写看起来像同步的代码,但实际上并非如此——它只是处理 Promise 的语法糖。

After fetch() sends the AJAX request, the browser continues loading the document. fetch()发送 AJAX 请求后,浏览器继续加载文档。 By the time it finishes, the DOM has been loaded and the DOMContentLoaded event has alrady fired, so it's too late to add an event listener for it.到它完成时,DOM 已经加载并且DOMContentLoaded事件已经触发,因此为它添加事件侦听器为时已晚。

You can get the promise from fetch() and use its .then() method from within the DOMContentLoaded listener.您可以从fetch() promise 并在DOMContentLoaded侦听器中使用其.then()方法。

 setProjects() { let response_promise = fetch("contents/projects.json"); document.addEventListener("DOMContentLoaded", function() { response_promise.then(response => response.json().then(responseJson => { var p = document.createElement('p'); p.innerHTML = responseJson.one.bio; p.id = "bio-project"; // p.style.cssText = 'border-left: 8px solid aqua;'; document.querySelector(".projeto-contents").appendChild(p); })) }, false) }

 document.addEventListener("DOMContentLoaded", async () => { const response = await fetch("contents/projects.json").then((res) => res.json()); const paragraph = document.createElement("p"); paragraph.innerHTML = response.one.bio; paragraph.id = "bio-project"; // p.style.cssText = 'border-left: 8px solid aqua;'; document.querySelector(".projeto-contents").appendChild(paragraph); });
 <,DOCTYPE html> <html lang="pt-br"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <title>Projetos - Vitor Hugo's Portifolio</title> <link rel="stylesheet" href="../style.css" /> <script defer src="./index.js"></script> </head> <body> <header> <nav> <a class="logo" href="/">Vitor Hugo</a> <div class="mobile-menu"> <div class="line-1"></div> <div class="line-2"></div> <div class="line-3"></div> </div> <ul class="nav-list"> <li><a href="index.html">Home</a></li> <li><a href="sobre.html">Sobre</a></li> <li><a href="projetos.html">Projetos</a></li> <li><a href="contatos.html">Contato</a></li> </ul> </nav> </header> <div class="projetos"> <div class="projeto-contents"> <h1 id="titulo-project">test</h1> </div> </div> </body> </html>

You're firing DOMContentLoaded after DOM was already rendered to your page.在 DOM 已经呈现到您的页面之后,您正在触发 DOMContentLoaded。 Also in your HTML in you're using without defer attribute.同样在您的 HTML 中,您正在使用没有defer属性。 Basically defer is telling browser to execute that script after document has been parsed or you can just append it at the of the body <script src="./index.js"></script> .基本上defer是告诉浏览器在文档被解析后执行该script ,或者您可以在正文<script src="./index.js"></script>处执行 append 它。

Also i'm using Promise API, if you want to know more about it check PromiseAPI or about async/await另外我正在使用 Promise API,如果您想了解更多信息,请查看PromiseAPI异步/等待

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM