js 学习笔记,主要参考: 白月黑羽。
JavaScript 简介
- 发明 js 的目的,就是放在网页中,让网页动起来。
- 应用场景:网站的用户登录页面,用户输入用户名和密码后,使用JavaScript(以后简称 js)代码做校验后,发送给服务端。订单查询系统,js 代码从服务端查询出订单数据,再由 js 代码负责动态更新网页html,呈现在网页上。
- js 是解释型的编程语言,由 js 解释器解释执行。
- 浏览器都内置了 js 解释器。
- Node.js 是一个独立的 js 解释器。
一、代码编辑软件
使用 WebStorm
二、网页中的 js
浏览器中的 js 的几个重要能力
- 获取网页的内容
- 更改网页的内容
- 当某个事情发生时得到通知
- 和服务端进行通讯
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.center-child {
display: flex;
justify-content: center;
}
</style>
<script>
function postLoginRequest() {
let username = document.querySelector("#username").value;
let password = document.querySelector("#password").value;
let eInfo = "";
/**
* 如果 username 长度小于 6,输出用户名错误提示
* 如果 username 长度符合要求,则判断 password 的长度
*
* */
if (username.length < 6) {
eInfo = `用户名: ${username}错误,至少为6位字符`;
} else if (password.length !== 6) {
eInfo = `密码: ${password}错误,必须为6位`;
}
document.querySelector("#errInfo").innerText = eInfo;
// 与服务端通讯功能还不懂,后续补充
}
function inputCheck() {
// 获取网页的内容
let password = document.querySelector("#password").value;
let eInfo = "";
if (password.length !== 6) {
eInfo = `密码:${password}错误,密码必须为6位`;
}
// 修改网页的内容
// 当密码框的值发生变化时,在网页上通知用户
document.querySelector("#errInfo").innerText = eInfo;
}
</script>
</head>
<body>
<!-- 输入区 -->
<div class="center-child">
<div style="margin-top: 5em;">
<p>输入用户名、密码</p>
<input type="text" id="username" class="form-control" placeholder="用户名">
<br>
<br>
<input type="password" id="password" class="form-control" placeholder="密码" oninput="inputCheck()">
<br>
<br>
<div class="center-child">
<button style="margin: 0 auto; " onclick="postLoginRequest()">登录</button>
</div>
</div>
</div>
<!-- 提示信息 -->
<div class="center-child">
<p style="color: red; " id="errInfo"></p>
</div>
</body>
</html>
三、html 内嵌 js 代码
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Document</title>
<!-- 内嵌在 head 中 -->
<script>
function addElement() {
document.querySelector("body").insertAdjacentHTML("beforeend", "<h1>今日新闻</h1>");
}
</script>
</head>
<body>
<script>
addElement();
</script>
<span id="version" class="title" style="color: blue; ">我的网站@2025</span>
<br>
<br>
<!-- 内嵌在 body 中 -->
<script>
<!-- 在 body 的(当前)最后一个子节点后面插入 -->
document.querySelector("body").insertAdjacentHTML("beforeend", "<span>谢谢大家</span>");
</script>
</body>
</html>
四、html 引用外部 js 代码文件
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Document</title>
<!-- 引用外部 js 代码文件 -->
<script src="./js.js"></script>
</head>
<body>
<script>
addElement1();
</script>
<span id="version" class="title" style="color: blue; ">我的网站@2025</span>
<br>
<br>
<script>
addElement2();
</script>
</body>
</html>
js文件
function addElement1() {
document.querySelector("body").insertAdjacentHTML("beforeend", "<h1>今日新闻</h1>");
}
function addElement2() {
document.querySelector("body").insertAdjacentHTML("beforeend", "<span>谢谢大家</span>");
}