首页 web前端 js教程 掌握 JavaScript 和 DOM 操作

掌握 JavaScript 和 DOM 操作

Aug 06, 2024 am 04:05 AM

介绍

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中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

<🎜>:泡泡胶模拟器无穷大 - 如何获取和使用皇家钥匙
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系统,解释
3 周前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆树的耳语 - 如何解锁抓钩
3 周前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

Java教程
1666
14
CakePHP 教程
1426
52
Laravel 教程
1328
25
PHP教程
1273
29
C# 教程
1254
24
JavaScript引擎:比较实施 JavaScript引擎:比较实施 Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和执行JavaScript代码时,效果会有所不同,因为每个引擎的实现原理和优化策略各有差异。1.词法分析:将源码转换为词法单元。2.语法分析:生成抽象语法树。3.优化和编译:通过JIT编译器生成机器码。4.执行:运行机器码。V8引擎通过即时编译和隐藏类优化,SpiderMonkey使用类型推断系统,导致在相同代码上的性能表现不同。

Python vs. JavaScript:学习曲线和易用性 Python vs. JavaScript:学习曲线和易用性 Apr 16, 2025 am 12:12 AM

Python更适合初学者,学习曲线平缓,语法简洁;JavaScript适合前端开发,学习曲线较陡,语法灵活。1.Python语法直观,适用于数据科学和后端开发。2.JavaScript灵活,广泛用于前端和服务器端编程。

从C/C到JavaScript:所有工作方式 从C/C到JavaScript:所有工作方式 Apr 14, 2025 am 12:05 AM

从C/C 转向JavaScript需要适应动态类型、垃圾回收和异步编程等特点。1)C/C 是静态类型语言,需手动管理内存,而JavaScript是动态类型,垃圾回收自动处理。2)C/C 需编译成机器码,JavaScript则为解释型语言。3)JavaScript引入闭包、原型链和Promise等概念,增强了灵活性和异步编程能力。

JavaScript和Web:核心功能和用例 JavaScript和Web:核心功能和用例 Apr 18, 2025 am 12:19 AM

JavaScript在Web开发中的主要用途包括客户端交互、表单验证和异步通信。1)通过DOM操作实现动态内容更新和用户交互;2)在用户提交数据前进行客户端验证,提高用户体验;3)通过AJAX技术实现与服务器的无刷新通信。

JavaScript在行动中:现实世界中的示例和项目 JavaScript在行动中:现实世界中的示例和项目 Apr 19, 2025 am 12:13 AM

JavaScript在现实世界中的应用包括前端和后端开发。1)通过构建TODO列表应用展示前端应用,涉及DOM操作和事件处理。2)通过Node.js和Express构建RESTfulAPI展示后端应用。

了解JavaScript引擎:实施详细信息 了解JavaScript引擎:实施详细信息 Apr 17, 2025 am 12:05 AM

理解JavaScript引擎内部工作原理对开发者重要,因为它能帮助编写更高效的代码并理解性能瓶颈和优化策略。1)引擎的工作流程包括解析、编译和执行三个阶段;2)执行过程中,引擎会进行动态优化,如内联缓存和隐藏类;3)最佳实践包括避免全局变量、优化循环、使用const和let,以及避免过度使用闭包。

Python vs. JavaScript:社区,图书馆和资源 Python vs. JavaScript:社区,图书馆和资源 Apr 15, 2025 am 12:16 AM

Python和JavaScript在社区、库和资源方面的对比各有优劣。1)Python社区友好,适合初学者,但前端开发资源不如JavaScript丰富。2)Python在数据科学和机器学习库方面强大,JavaScript则在前端开发库和框架上更胜一筹。3)两者的学习资源都丰富,但Python适合从官方文档开始,JavaScript则以MDNWebDocs为佳。选择应基于项目需求和个人兴趣。

Python vs. JavaScript:开发环境和工具 Python vs. JavaScript:开发环境和工具 Apr 26, 2025 am 12:09 AM

Python和JavaScript在开发环境上的选择都很重要。1)Python的开发环境包括PyCharm、JupyterNotebook和Anaconda,适合数据科学和快速原型开发。2)JavaScript的开发环境包括Node.js、VSCode和Webpack,适用于前端和后端开发。根据项目需求选择合适的工具可以提高开发效率和项目成功率。

See all articles