操作DOM
html代码
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<label>
<input id="name">
<button id="button">获取值</button>
<input id="show">
<div id="container"></div>
<div id="table">
<li class="li">1</li>
<li class="li">2</li>
<li class="li">3</li>
<li class="li">4</li>
<li class="li">5</li>
<li class="li">6</li>
</div>
</label>
</body>
<script src="/static/js/demo.js"></script>
</html>
js代码
// 获取按钮
button = document.getElementById("button")
// 按钮绑定点击事件
button.onclick = function () {
// 获取输入框的值
const name = document.getElementById("name").value
// 在控制台打印输入框的值
console.log(name)
// 获取p标签
const show = document.getElementById("show")
// 修改show的文本
show.value = name
// 获取容器标签
const container = document.getElementById("container")
// 清空容器
container.innerHTML = ""
// 创建新标签
const element = document.createElement("h1")
element.textContent = name
// 向容器内添加元素
container.append(element)
// 获取指定标签下的所有li类型的标签
const lis = document.querySelectorAll("#table .li")
console.log(lis)
// 循环遍历
lis.forEach(li => {
console.log(li.textContent)
// 修改li的className
li.className = "litextContent"
})
}
发起请求
发起GET请求
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
</div>
<script>
// 定义url
const url = "/get_demo"
// 获取全局变量 app 标签
let app = document.getElementById("app")
// 准备传参
const params = new URLSearchParams({
name: "tom",
age: 18
})
// 定义方法
async function f() {
try {
// 发起请求
const response = await fetch(`${url}?${params.toString()}`)
console.log("请求状态:", response.status, "是否成功:", response.ok)
// 状态是OK
if (response.ok) {
// 获取返回的json
const data = await response.json()
console.log("返回数据:", data)
// 创建一个h1标签,用来显示 data.hello
const h1 = document.createElement("h1")
h1.textContent = data.hello
// 创建一个p标签,用来显示 data.hello.name
const p1 = document.createElement("p")
p1.textContent = `${data.data.name}`
// 把新建的标签添加进 app
app.append(h1)
app.append(p1)
// 获取列表
const dataList = data.list
// 创建父容器lo
const lo = document.createElement("ol")
// 遍历列表,创建标签li
dataList.forEach(i => {
const li = document.createElement("li")
li.textContent = i
// 添加到lo
lo.append(li)
})
// 把lo添加到app
app.append(lo)
} else {
console.error("请求失败")
}
} catch (err) {
console.error("请求异常:", err)
}
}
// 调用方法
f()
</script>
</body>
</html>
快速发起GET请求
const url = "/get1"
fetch(url)
.then(response => {
if (!response.ok) throw new Error("HTTP error " + response.status)
return response.json()
})
.then(data => {
console.log("JSON 数据:", data)
})
.catch(err => {
console.error("请求失败:", err)
})
发起POST请求
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="#" id="login">
<input id="name">
<hr>
<input id="passwd">
<hr>
<button id="button">登录</button>
</form>
<script>
const url = "/post_demo"
let button = document.getElementById("button")
async function f() {
// 获取表单的值
const name = document.getElementById("name").value
const passwd = document.getElementById("passwd").value
console.log(name, passwd)
// 发起POST请求
const response = await fetch(url, {
// 定义请求方式
method: "post",
// 定义请求体类型
headers: {
'Content-Type': 'application/json'
},
// 定义传参
body: JSON.stringify({
name: name,
passwd: passwd
})
})
// 打印返回体
if (response.ok) {
const data = await response.json()
console.log(data,data.name)
}
}
// button的点击事件绑定为f方法
button.onclick = f
</script>
</body>
</html>
快速发起POST
const url = "/post_demo"
const btn = document.getElementById("button")
btn.onclick = async () => {
const name = document.getElementById("name").value
const passwd = document.getElementById("passwd").value
const res = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, passwd })
})
if (!res.ok) return
const data = await res.json()
console.log(data.name)
}
事件处理
DOM事件和定时器
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="btn"><h1>我是按钮1</h1></div>
<div id="btn2"><h1>我是按钮2</h1></div>
<div id="stop"><h1>停止定时器</h1></div>
<button id="jump">跳转事件</button>
<script>
// 快速绑定点击事件
const btn = document.getElementById('btn');
btn.addEventListener('click', function () {
console.log('按钮1被点击了');
});
// 声明后绑定点击事件
const btn2 = document.getElementById('btn2');
function btnf2() {
console.log('按钮2被点击了');
}
btn2.onclick = btnf2
// 跳转事件
const jump = document.getElementById('jump');
jump.addEventListener("click", () => {
// 普通跳转
// window.location.href = 'https://example.com';
// 新标签页跳转
// window.open('https://example.com', '_blank');
window.location.replace('https://030399.xyz');
})
// 定时循环任务
function f() {
console.log('每秒执行一次');
}
// 绑定到定时器
const timer = setInterval(f, 1000);
// 匿名函数写法
const timer2 = setInterval(() => {
console.log('每秒执行2次');
}, 500)
const stopBtn = document.getElementById('stop');
stopBtn.addEventListener("click", function () {
// 取消定时器
clearTimeout(timer)
clearTimeout(timer2)
//延迟执行
setTimeout(() => {
console.log('3秒后执行');
}, 3000);
})
</script>
</body>
</html>
完整DEMO
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>前端完整 Demo</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 40px;
}
input {
display: block;
margin: 10px 0;
padding: 6px;
width: 200px;
}
button {
padding: 6px 12px;
cursor: pointer;
}
#userInfo {
margin-top: 20px;
display: none;
}
</style>
</head>
<body>
<h2>登录 Demo</h2>
<input id="username" placeholder="用户名">
<input id="password" type="password" placeholder="密码">
<button id="loginBtn">登录</button>
<div id="userInfo">
<h3>用户信息</h3>
<p>用户名:<span id="showName"></span></p>
<p>在线时间:<span id="timer">0</span> 秒</p>
</div>
<script>
// ===== DOM 获取 =====
const loginBtn = document.getElementById('loginBtn');
const usernameInput = document.getElementById('username');
const passwordInput = document.getElementById('password');
const userInfo = document.getElementById('userInfo');
const showName = document.getElementById('showName');
const timerEl = document.getElementById('timer');
let timer = null;
let seconds = 0;
// ===== 事件处理 =====
loginBtn.addEventListener('click', () => {
const username = usernameInput.value;
const password = passwordInput.value;
if (!username || !password) {
alert('请输入用户名和密码');
return;
}
login(username, password);
});
// ===== 模拟 POST 请求 =====
function login(username, password) {
console.log('发送登录请求', username, password);
mockRequest({
username,
password
}).then(res => {
onLoginSuccess(res);
});
}
// ===== 登录成功后的处理 =====
function onLoginSuccess(data) {
// 修改 DOM 内容
showName.innerText = data.username;
// 显示用户区域
userInfo.style.display = 'block';
// 禁用登录按钮
loginBtn.disabled = true;
// 启动定时器
startTimer();
}
// ===== 定时任务 =====
function startTimer() {
timer = setInterval(() => {
seconds++;
timerEl.innerText = seconds;
}, 1000);
}
// ===== 模拟后端请求 =====
function mockRequest(body) {
return new Promise(resolve => {
setTimeout(() => {
resolve({
code: 0,
username: body.username
});
}, 1000);
});
}
</script>
</body>
</html>