首頁 > web前端 > js教程 > 主體

掌握 JavaScript 和 DOM 操作

WBOY
發布: 2024-08-06 04:05:34
原創
504 人瀏覽過

介紹

Mastering JavaScript and DOM Manipulation

在本實驗室中,您將透過 Alex 的視角進入 Web 開發的世界,Alex 是一位嶄露頭角的 Web 開發人員,其任務是創建動態的個人財務追蹤器。建立一個用戶友好的應用程序,允許用戶輸入和追蹤他們的日常支出和收入。目標很明確 - 開發一個直觀又有吸引力的介面,確保用戶可以輕鬆管理他們的財務,沒有任何麻煩。此專案不僅旨在簡化個人財務管理,還向您介紹 JavaScript 和 DOM 操作的基本概念。

我們將透過 5 個實驗室來完成 EconoMe 專案。

Mastering JavaScript and DOM Manipulation

知識點

  • 變數宣告(let、const)
  • DOM 操作基礎(取得元素、修改元素內容)
  • 事件監聽(addEventListener)

基本 JavaScript

JavaScript 是一種簡單、物件導向、事件驅動的語言。它從伺服器下載到客戶端並由瀏覽器執行。

它可以與 HTML 和 Web 一起使用,並且更廣泛地用於伺服器、PC、筆記型電腦、平板電腦和智慧型手機。

其特點包括:

  • 通常用於編寫客戶端腳本。
  • 主要用於在HTML頁面中加入互動行為。
  • 它是一種解釋性語言,在解釋時執行。

那麼,我們如何在 HTML 中包含 JavaScript?

包含方法與CSS類似,可以用三種方式完成:

  • 直接在 HTML 標籤中,適用於特別短的 JavaScript 程式碼。
  • 使用標籤,JavaScript程式碼可以嵌入中。和 HTML 文件的。
  • 使用外部 JavaScript 文件,將 JavaScript 腳本程式碼寫入帶有 .js 後綴的文件中,並透過設定 <script> 的 src 屬性來包含它。標籤。 </script>

例如,如果我們按F12,我們可以看到該頁面中包含了很多外部JavaScript文件,透過點擊Event Listeners,我們可以觀察到該頁面中存在多種類型的事件頁。

Mastering JavaScript and DOM Manipulation

現在,讓我們加入 <script>;標籤 ~/project/index.html 以包含 script.js 檔案。 <br> </script>

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>EconoMe</title>
    <link rel="stylesheet" href="./style.css" />
    <!-- Add the script tag to index.html -->
    <script src="./script.js"></script>
  </head>
  <body></body>
</html>
登入後複製

接下來,我們來學習如何在 JavaScript 中定義變數!

什麼是變數

變數可以看作是儲存資訊的容器。在程式設計中,我們使用變數來儲存資料值。 JavaScript 是一種動態類型語言,這表示您不需要宣告變數的類型。類型會在程式執行過程中自動決定。

宣告變數

在 JavaScript 中,您可以使用 var、let 或 const 關鍵字來宣告變數:

  • var:在 ES6 之前,var 是宣告變數的主要方式,並且它具有函數作用域。
  • let:ES6 中引入,let 可讓您宣告區塊作用域的局部變數。
  • const:ES6中也引入了,用於聲明一個常數,一旦聲明就不能改變。

例如:

var name = "Alice"; // Using var to declare a variable
let age = 30; // Using let to declare a variable
const city = "London"; // Using const to declare a constant
登入後複製

變數的類型

在 JavaScript 中,有幾種不同的資料型別:

  • 字串:文字數據,例如「Hello,World!」。
  • 數字:整數或浮點數,例如 42 或 3.14。
  • 布林值:真或假。
  • 物件:可以儲存多個值或複雜的資料結構。
  • null 和 undefined:分別表示「無值」和「值未定義」的特殊類型。

使用變數

宣告變數後,您可以在程式中使用它們:

console.log(name); // Outputs: Alice
console.log("Age: " + age); // Outputs: Age: 30
console.log(city + " is a beautiful city"); // Outputs: London is a beautiful city
登入後複製

console.log() 靜態方法向控制台輸出一則訊息。

Mastering JavaScript and DOM Manipulation

DOM操作

DOM (Document Object Model) 是一個跨平台、與語言無關的接口,它將HTML 和XML 文件視為樹結構,其中每個節點都是文件的一部分,例如元素、屬性和文字內容。

Accessing DOM Elements

To manipulate the content of a web page, you first need to access the elements in the DOM tree. You can use various methods to access elements, such as by their ID, class name, or tag name:

let elementById = document.getElementById("elementId"); // Access element by ID
let elementsByClassName = document.getElementsByClassName("className"); // Access a collection of elements by class name
let elementsByTagName = document.getElementsByTagName("tagName"); // Access a collection of elements by tag name
登入後複製

Add the following code to the ~/project/script.js file of the EconoMe project:

const form = document.getElementById("record-form");
const recordsList = document.getElementById("records-list");
const totalIncomeEl = document.getElementById("total-income");
const totalExpenseEl = document.getElementById("total-expense");
const balanceEl = document.getElementById("balance");
登入後複製

Modifying Element Content

Once you have a reference to an element, you can modify its content. The innerHTML and textContent properties are commonly used for this purpose.

For example, to insert

New HTML content

into a div element with id=content and replace "Hello" with "New text content" in a span element with id=info, you would use the following JavaScript code:

Mastering JavaScript and DOM Manipulation

Adding and Removing Elements

You can dynamically add or remove elements on the page using JavaScript.

For example:

// Create a new element
let newElement = document.createElement("div");
newElement.textContent = "Hello, world!";
document.body.appendChild(newElement); // Add the new element to the document body
document.body.removeChild(newElement); // Remove the element from the document body
登入後複製
  • In an HTML document, the document.createElement() method creates the HTML element.
  • The document.body.appendChild() method adds the new element to the end of the element.
  • The document.body.removeChild() method removes the element from the element.

Event Handling

Event listeners allow you to respond to user actions.

addEventListener("event", function () {});
登入後複製

such as clicks, hover, or key presses:

elementById.addEventListener("click", function () {
  console.log("Element was clicked!");
});
登入後複製

Mastering JavaScript and DOM Manipulation

After learning the basic DOM operations, you can add the following code to the ~/project/script.js file of the EconoMe project:

document.addEventListener("DOMContentLoaded", function () {
  const form = document.getElementById("record-form");
  const recordsList = document.getElementById("records-list");
  const totalIncomeEl = document.getElementById("total-income");
  const totalExpenseEl = document.getElementById("total-expense");
  const balanceEl = document.getElementById("balance");
  let draggedIndex = null; // Index of the dragged item
});
登入後複製

The DOMContentLoaded event in JavaScript is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. This makes it an important event for running JavaScript code as soon as the DOM is ready, ensuring that the script interacts with fully parsed HTML elements.

This lab does not require previewing the effect at this point. We will review it after completing the code in the following steps.

Summary

In this lab, you embarked on the journey of building a basic yet fundamental part of a personal finance tracker with Alex. You've set the stage for a dynamic web application by setting up the project environment and using JavaScript to manipulate the DOM, showing initial financial states. The key takeaway is understanding how JavaScript interacts with HTML elements to dynamically change the content of a web page, laying the groundwork for more interactive features in the following steps.

This hands-on approach not only solidifies your understanding of JavaScript and DOM manipulation but also simulates real-world web development scenarios, preparing you for more complex projects ahead.


? Practice Now: Basic JavaScript and DOM


Want to Learn More?

  • ? Learn the latest JavaScript Skill Trees
  • ? Read More JavaScript Tutorials
  • ? Join our Discord or tweet us @WeAreLabEx

以上是掌握 JavaScript 和 DOM 操作的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!