【问题标题】:getting null value in span element在 span 元素中获取空值
【发布时间】:2021-07-29 23:32:39
【问题描述】:

当我尝试运行我的 index.html 文件时

<div class="quote-text">
        <i class="fas fa-quote-left"></i>
        <span id="quote"></span>
    </div>
    <!-- author element -->
    <div class="quote-author">
        <span id="author"></span>
    </div>

我的 textContent 方法没有显示任何内容。

const quoteText = document.getElementById("quote");
const authorText = document.getElementById("author");

let apiQuotes = [] 

function newQuote(){
    const ranQuote = apiQuotes[Math.floor(Math.random() * apiQuotes.length)];
    console.log(ranQuote);
    console.log(ranQuote.text);
    console.log(ranQuote.author);
    console.log(quoteText);<!-- this shows null -->
    console.log(authorText); <!-- this shows null -->
    quoteText.textContent = ranQuote.text;
    authorText.textContent = ranQuote.author;
};

async function getQuotes(){
    const apiUrl = 'https://type.fit/api/quotes';
    try{
        const response = await fetch(apiUrl);
        apiQuotes = await response.json()
        newQuote();
    }
    catch(error){
    }
}

getQuotes();  

我在控制台记录了 span 元素值,并且它的记录为 null。而且我无法在 span 元素中更改我想要的值

this is console screeenshot

【问题讨论】:

    标签: javascript html json api console.log


    【解决方案1】:

    您的代码按预期运行,您可以在下面的 sn-p 中看到。 确保您在 创建 DOM 元素之后运行此脚本。 将您的脚本放在&lt;/body&gt; 之前,或者确保它在DOMContentLoaded 之后执行(下面的Stack sn-p 执行此操作^)

    const quoteText = document.getElementById("quote");
    const authorText = document.getElementById("author");
    
    let apiQuotes = []
    
    function newQuote() {
      const ranQuote = apiQuotes[Math.floor(Math.random() * apiQuotes.length)];
      console.log(ranQuote);
      console.log(ranQuote.text);
      console.log(ranQuote.author);
      console.log(quoteText); <!-- this shows null -->
      console.log(authorText); <!-- this shows null -->
      quoteText.textContent = ranQuote.text;
      authorText.textContent = ranQuote.author;
    };
    
    async function getQuotes() {
      const apiUrl = 'https://type.fit/api/quotes';
      try {
        const response = await fetch(apiUrl);
        apiQuotes = await response.json()
        newQuote();
      } catch (error) {}
    }
    
    getQuotes();
    <div class="quote-text">
      <i class="fas fa-quote-left"></i>
      <span id="quote">Wait for the request to finish...</span>
    </div>
    <!-- author element -->
    <div class="quote-author">
      <span id="author"></span>
    </div>

    【讨论】:

    • 刚刚看到我的脚本在正文之前运行。感谢您的帮助。
    • @ImBatman 考虑接受将问题标记为已解决的答案:stackoverflow.com/help/someone-answers
    • 哦,知道了,先生。我在这里有点新,所以不太了解。标记你的!
    猜你喜欢
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-21
    • 1970-01-01
    • 2020-08-02
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多