Ghid pas cu pas pentru construirea unui generator de cotații aleatoriu cu JavaScript

Bună! Sunt din nou eu, tipul JavaScript Tutorial. Acum voi crea o aplicație Generator de cotații aleatoriu folosind JavaScript. Da, știu că acesta este un tutorial de bază, dar totul începe de la bază, nu-i așa?

Voi începe prin a crea un Generator de cotații aleatoriu foarte simplu, datele de cotație sunt codificate în JavaScript și fără stil. Vreau doar să vă arăt principiul de bază cum să obțineți unele date dintr-o serie de date în interfața browserului, dacă înțelegeți acest lucru, veți înțelege cu ușurință cum să preluați date din API.

Ok, destulă introducere, haideți!

  1. Creați un fișier HTML, îl puteți numi orice doriți, prefer index.html și puneți acest cod:
<!DOCTYPE html>
<html lang="en">
  <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>Random Quote Generator</title>
  </head>
  <body>
    <div id="quote"></div>
    <button id="generate-btn">Generate Quote</button>
    <script src="script.js"></script>
  </body>
</html>
  1. Acum, după cum puteți vedea, am pus un buton cu id-ul generate-btn, acest buton va afișa un Citat dacă ați dat clic pe el
  2. Să creăm JavaScript în script.js
// An array of quotes to choose from
const quotes = [
  {
    quote:
      "The greatest glory in living lies not in never falling, but in rising every time we fall.",
    author: "Nelson Mandela",
  },
  {
    quote: "The way to get started is to quit talking and begin doing.",
    author: "Walt Disney",
  },
  {
    quote:
      "If life were predictable it would cease to be life, and be without flavor.",
    author: "Eleanor Roosevelt",
  },
  {
    quote: "Your time is limited, don't waste it living someone else's life.",
    author: "Steve Jobs",
  },
  {
    quote: "Life is what happens when you're busy making other plans.",
    author: "John Lennon",
  },
];

// Function to generate a random quote from the array
function generateQuote() {
  // Choose a random index from the array
  const index = Math.floor(Math.random() * quotes.length);

  // Get the quote object at the chosen index
  const quote = quotes[index];

  // Build a string with the quote and author
  const quoteString = `"${quote.quote}" - ${quote.author}`;

  // Set the text of the quote div to the generated string
  document.getElementById("quote").innerHTML = quoteString;
}

// Add an event listener to the button to generate a new quote when clicked
document
  .getElementById("generate-btn")
  .addEventListener("click", generateQuote);

Veți observa că am codificat citatul în JavaScript:

// An array of quotes to choose from
const quotes = [
  {
    quote:
      "The greatest glory in living lies not in never falling, but in rising every time we fall.",
    author: "Nelson Mandela",
  },
  {
    quote: "The way to get started is to quit talking and begin doing.",
    author: "Walt Disney",
  },
  {
    quote:
      "If life were predictable it would cease to be life, and be without flavor.",
    author: "Eleanor Roosevelt",
  },
  {
    quote: "Your time is limited, don't waste it living someone else's life.",
    author: "Steve Jobs",
  },
  {
    quote: "Life is what happens when you're busy making other plans.",
    author: "John Lennon",
  },
];

Vom numi acest lucru quote în cadrul funcției noastre generateQuote().
Să defalcăm funcția:

// Choose a random index from the array
  const index = Math.floor(Math.random() * quotes.length);
  • În prima linie a funcției noastre generateQuote(), ne vom indexa cotația folosind Math.floor și Math.random ori cotația totală pe care o avem folosind .length. Practic, dorim să generăm un număr aleatoriu între 0 - cota totală pe care o avem. Pentru mai multe despre Math.random și Math.floor, puteți verifica „aici”.
// Get the quote object at the chosen index
  const quote = quotes[index];
  • Pe a doua linie, vom captura indexarea aleatorie din variabila quote. De exemplu, dacă indicele aleator este 1, valoarea variabilei quote este quotes[1], care este citatul Walt Disney.
// Build a string with the quote and author
  const quoteString = `"${quote.quote}" - ${quote.author}`;
  • Acum, punem valoarea din tabloul quotes în quoteString. Ceea ce punem aici este valoarea din citatul ales din variabila quote la pasul 2.
// Set the text of the quote div to the generated string
  document.getElementById("quote").innerHTML = quoteString;
  • Da, s-ar putea să înțelegi deja ce este asta. Punem valoarea noastră quoteString în elementul nostru HTML cu un id de quote.
  • Ok, dar această funcție singură nu va face nimic fără să o numească. Să apelăm funcția făcând clic pe generate-btn pe care am pus-o înainte în HTML-ul nostru
// Add an event listener to the button to generate a new quote when clicked
document
  .getElementById("generate-btn")
  .addEventListener("click", generateQuote);

Acum dețineți generatorul de cotații aleatoriu funcțional, treabă bună până acum! Acum înțelegeți principiul de bază cum să consumați unele date și să le puneți în vizualizarea browserului.

În continuare, vom îmbunătăți acest Generator de cotații aleatoriu consumând un API. Ne vedem mai târziu la următorul tutorial!

Sprijină-mă la Cumpără-mi o cafea, dacă găsești această postare utilă făcând clic pe butonul Dă un pont de mai jos ☕. Urmărește-mă pe Twitter @DevMazaya.