簡體   English   中英

我不知道為什么我的函數不能讀取quotesdata

[英]i don't know why my function can not read quotesdata

我不知道為什么我在 addEventListener 中的函數無法讀取引號數據,這是我在控制台中看到的:

未捕獲的類型錯誤:quotesData[currentQuote] 未定義,這是 js 代碼:

quotesData = [
    {
        quote : `There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.`,
        name : 'Albert Einstein '
    },
    {
        quote : `Good friends, good books, and a sleepy conscience: this is the ideal life.`,
        name : 'Mark Twain'
    },
    {
        quote : `Life is what happens to us while we are making other plans.`,
        name : 'Allen Saunders '
    },
    {
        quote : `It's not the load that breaks you down, it's the way you carry it.`,
        name : 'Lou Holt'
    },
    {
        quote : `Try not to become a man of success. Rather become a man of value.`,
        name : 'Albert Einstein '
    },   
]
/* important variables */ 
let currentQuote = quotesData[0];
const quoteText = document.getElementById('quote');
const quotebtn = document.getElementById('q-btn');
const quotespan = document.getElementById('q-span');

/* this the main function its usefulness is show a quote from quotesData evrey time you click on the button*/ 
quotebtn.addEventListener('click' , () => {
    quoteText.innerText = quotesData[currentQuote].quote;
    quotespan.innerText = quotesData[currentQuote].name; 
    
    currentQuote = (currentQuote + 1 ) % quotesData.length;
});

您需要在currentQuote存儲索引,而不是當前報價的對象:

 quotesData = [ { quote : `There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle.`, name : 'Albert Einstein ' }, { quote : `Good friends, good books, and a sleepy conscience: this is the ideal life.`, name : 'Mark Twain' }, { quote : `Life is what happens to us while we are making other plans.`, name : 'Allen Saunders ' }, { quote : `It's not the load that breaks you down, it's the way you carry it.`, name : 'Lou Holt' }, { quote : `Try not to become a man of success. Rather become a man of value.`, name : 'Albert Einstein ' }, ] /* important variables */ let currentQuote = 0; const quoteText = document.getElementById('quote'); const quotebtn = document.getElementById('q-btn'); const quotespan = document.getElementById('q-span'); /* this the main function its usefulness is show a quote from quotesData evrey time you click on the button*/ quotebtn.addEventListener('click' , () => { quoteText.innerText = quotesData[currentQuote].quote; quotespan.innerText = quotesData[currentQuote].name; currentQuote = (currentQuote + 1) % quotesData.length; });
 <button id="q-btn">New quote</button> <div id="q-span"></div> <div id="quote"></div>

我不確定,但我認為您可能使用的是“密鑰”而不是“密鑰”。 我認為您可能希望將開頭和結尾的所有引號更改為 " 以確保安全。我可能不對,但這是我能想到的唯一解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM