本文详细介绍了从JavaScript基础知识到实战项目的全过程,涵盖了变量、数据类型、条件语句、循环、函数、面向对象编程等内容。接着,文章指导读者搭建开发环境,包括编辑器选择、Node.js和npm安装,以及版本控制。随后,通过简易待办事项列表应用和天气查询应用两个实战项目,进一步巩固所学知识。通过这些步骤,读者可以轻松掌握JavaScript项目实战技巧。
Javascript项目实战入门教程在JavaScript中,变量用于存储数据。JavaScript是一种动态类型语言,这意味着你不需要在声明变量时指定类型。
变量声明:
let age = 25; // 使用let关键字声明变量 const name = "Alice"; // 使用const关键字声明常量
let num = 123;
let str = "Hello, world!";
let isTrue = true;
let nothing = null;
let variable;
let obj = { name: "Alice", age: 25 };
let unique = Symbol("unique");
let arr = [1, 2, 3];
条件语句:
let age = 18; if (age >= 18) { console.log("成年人"); } else { console.log("未成年人"); } let score = 85; switch (score) { case 90: console.log("优秀"); break; case 80: console.log("良好"); break; default: console.log("一般"); }
循环:
for (let i = 0; i < 5; i++) { console.log(i); } let i = 0; while (i < 5) { console.log(i); i++; } let arr = [1, 2, 3]; for (let value of arr) { console.log(value); }
函数定义:
function greet(name) { return `Hello, ${name}!`; } console.log(greet("Alice")); // 箭头函数 const square = (num) => num * num; console.log(square(4));
作用域:
let globalVar = "全局变量"; function localScope() { let localVar = "局部变量"; console.log(globalVar); // 全局变量 console.log(localVar); // 局部变量 } localScope(); console.log(globalVar); // 全局变量 console.log(localVar); // 报错:localVar未定义
构造函数:
function Person(name, age) { this.name = name; this.age = age; } Person.prototype.greet = function() { return `Hello, my name is ${this.name} and I am ${this.age} years old.`; }; let alice = new Person("Alice", 25); console.log(alice.greet()); // Hello, my name is Alice and I am 25 years old.
Node.js是一个用于运行JavaScript代码的环境,npm是Node.js的包管理器。
node -v npm -v
index.html
文件和一个script.js
文件。在index.html
中引入script.js
:
<!DOCTYPE html> <html> <head> <title>我的第一个项目</title> </head> <body> <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="script.js"></script> </body> </html>
配置index.html
和script.js
文件:
index.html
示例代码:
<!DOCTYPE html> <html> <head> <title>简易待办事项列表</title> </head> <body> <div> <input id="input" type="text" placeholder="请输入待办事项"> <ul id="list"></ul> </div> <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="script.js"></script> </body> </html>
script.js
示例代码:
document.getElementById("input").addEventListener("keydown", function(event) { if (event.key === "Enter") { let input = document.getElementById("input"); let list = document.getElementById("list"); let value = input.value; if (value) { let li = document.createElement("li"); li.textContent = value; let deleteButton = document.createElement("span"); deleteButton.textContent = "删除"; deleteButton.className = "delete"; deleteButton.addEventListener("click", function() { list.removeChild(li); }); li.appendChild(deleteButton); list.appendChild(li); input.value = ""; } } });
使用命令行工具初始化Git仓库:
git init
添加文件到暂存区:
git add .
git commit -m "初始化项目"
创建HTML文件index.html
:
<!DOCTYPE html> <html> <head> <title>简易待办事项列表</title> <style> /* 基础样式 */ body { font-family: Arial, sans-serif; margin: 0; padding: 0; } #app { padding: 20px; } #input { width: 60%; padding: 10px; margin-bottom: 20px; } #list { list-style-type: none; padding: 0; } #list li { background: #f9f9f9; margin-bottom: 10px; padding: 10px; border: 1px solid #ddd; } #list li.completed { text-decoration: line-through; background: #eee; } #list li .delete { float: right; cursor: pointer; } </style> </head> <body> <div id="app"> <input id="input" type="text" placeholder="请输入待办事项"> <ul id="list"></ul> </div> <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="script.js"></script> </body> </html>
在script.js
中添加功能代码:
document.getElementById("input").addEventListener("keydown", function(event) { if (event.key === "Enter") { let input = document.getElementById("input"); let list = document.getElementById("list"); let value = input.value; if (value) { let li = document.createElement("li"); li.textContent = value; let checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.addEventListener("change", function() { li.classList.toggle("completed"); }); li.appendChild(checkbox); let deleteButton = document.createElement("span"); deleteButton.textContent = "删除"; deleteButton.className = "delete"; deleteButton.addEventListener("click", function() { list.removeChild(li); }); li.appendChild(deleteButton); list.appendChild(li); input.value = ""; } } });
使用本地存储保存待办事项:
function saveToLocalStorage() { let list = document.getElementById("list"); let items = []; for (let item of list.children) { items.push(item.textContent); } localStorage.setItem("todos", JSON.stringify(items)); } function loadFromLocalStorage() { let list = document.getElementById("list"); let items = JSON.parse(localStorage.getItem("todos") || "[]"); for (let item of items) { let li = document.createElement("li"); li.textContent = item; let checkbox = document.createElement("input"); checkbox.type = "checkbox"; checkbox.addEventListener("change", function() { li.classList.toggle("completed"); }); li.appendChild(checkbox); let deleteButton = document.createElement("span"); deleteButton.textContent = "删除"; deleteButton.className = "delete"; deleteButton.addEventListener("click", function() { list.removeChild(li); }); li.appendChild(deleteButton); list.appendChild(li); } } loadFromLocalStorage(); document.getElementById("input").addEventListener("keydown", function(event) { if (event.key === "Enter") { // 添加待办事项的逻辑 saveToLocalStorage(); } });
.env
文件:
API_KEY=YOUR_API_KEY
在HTML文件中添加输入框和显示区域:
<!DOCTYPE html> <html> <head> <title>天气查询应用</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 0; } #app { padding: 20px; } #input { width: 60%; padding: 10px; margin-bottom: 20px; } #weather { padding: 10px; border: 1px solid #ddd; } </style> </head> <body> <div id="app"> <input id="input" type="text" placeholder="请输入城市名"> <div id="weather"></div> </div> <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="script.js"></script> </body> </html>
使用fetch请求API:
document.getElementById("input").addEventListener("keydown", function(event) { if (event.key === "Enter") { let input = document.getElementById("input"); let weatherDiv = document.getElementById("weather"); let city = input.value; fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.API_KEY}&units=metric`) .then(response => response.json()) .then(data => { weatherDiv.innerHTML = `<p>城市: ${data.name}</p> <p>温度: ${data.main.temp} °C</p> <p>湿度: ${data.main.humidity}%</p> <p>天气状况: ${data.weather[0].description}</p>`; }) .catch(error => { weatherDiv.textContent = "未能获取天气数据"; }); input.value = ""; } });
在服务器响应错误时显示错误消息:
document.getElementById("input").addEventListener("keydown", function(event) { if (event.key === "Enter") { let input = document.getElementById("input"); let weatherDiv = document.getElementById("weather"); let city = input.value; fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.API_KEY}&units=metric`) .then(response => { if (!response.ok) { throw new Error("未能获取天气数据"); } return response.json(); }) .then(data => { weatherDiv.innerHTML = `<p>城市: ${data.name}</p> <p>温度: ${data.main.temp} °C</p> <p>湿度: ${data.main.humidity}%</p> <p>天气状况: ${data.weather[0].description}</p>`; }) .catch(error => { weatherDiv.textContent = "未能获取天气数据"; }); input.value = ""; } });
使用浏览器开发者工具检查代码:
console.log("调试信息");
.github/workflows/pages.yml
文件以自动化部署:
name: Pages on: push: branches: [ main ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Setup Node uses: actions/setup-node@v2 with: node-version: '14.x' - name: Install Dependencies run: npm install - name: Build run: npm run build - name: Deploy to GitHub Pages uses: peaceiris/actions-gh-pages@v3 with: build-dir: ./dist publish-dir: ./dist github-token: ${{ secrets.GITHUB_TOKEN }}
<!DOCTYPE html> <html> <head> <title>我的项目</title> <script class="lazyload" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAANSURBVBhXYzh8+PB/AAffA0nNPuCLAAAAAElFTkSuQmCC" data-original="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <script> $(document).ready(function() { console.log("jQuery 已加载"); }); </script> </body> </html>
TypeError:通常表示尝试使用非法值。
let x = null; console.log(x + 1); // TypeError: null + 1 is not a number console.log(typeof x); // 输出:object console.log(x === null); // 输出:true
ReferenceError:通常表示尝试引用不存在的变量。
let y; console.log(y); // ReferenceError: y is not defined
console.log("test"; // SyntaxError: missing ) after condition console.log("test"); // 正确
避免全局变量:尽量减少使用全局变量。
let globalVar = "全局变量";
let
和const
,箭头函数,模板字符串等新特性。
const square = (num) => num * num;
通过以上介绍,您可以从基础到实战逐步掌握JavaScript项目开发的全过程。希望本教程能帮助您更好地理解和实践JavaScript。