操作 DOM

DOM(文档对象模型)是 JavaScript 与网页交互的桥梁。通过 DOM,JavaScript 可以动态地读取、修改页面元素。

HTML 结构

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>DOM 操作演示</title>
</head>
<body>
    <label>
        <input id="name" placeholder="请输入内容">
        <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>

JavaScript 代码

// 获取按钮元素
const button = document.getElementById("button");

// 绑定点击事件
button.onclick = function () {
    // 获取输入框的值
    const name = document.getElementById("name").value;
    console.log(name);

    // 修改另一个输入框的值
    const show = document.getElementById("show");
    show.value = name;

    // 创建新元素并添加到容器
    const container = document.getElementById("container");
    container.innerHTML = ""; // 清空容器
    const element = document.createElement("h1");
    element.textContent = name;
    container.append(element);

    // 选择并遍历所有指定元素
    const lis = document.querySelectorAll("#table .li");
    console.log(lis);

    lis.forEach(li => {
        console.log(li.textContent);
        li.className = "litextContent";
    });
};

核心 API 总结

方法 说明
getElementById() 通过 ID 获取单个元素
querySelectorAll() 通过选择器获取元素集合
createElement() 创建新元素
append() 追加子元素
innerHTML 获取或设置 HTML 内容
textContent 获取或设置文本内容

发起请求

使用 fetch API 可以方便地发起网络请求,支持 GET、POST 等多种方法。

GET 请求

完整示例

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>GET 请求示例</title>
</head>
<body>
    <div id="app"></div>
    <script>
        const url = "/get_demo";
        const app = document.getElementById("app");

        async function fetchData() {
            try {
                // 准备查询参数
                const params = new URLSearchParams({
                    name: "tom",
                    age: 18
                });

                // 发起 GET 请求
                const response = await fetch(`${url}?${params.toString()}`);
                console.log(`状态: ${response.status}, 成功: ${response.ok}`);

                if (response.ok) {
                    const data = await response.json();
                    console.log("返回数据:", data);

                    // 渲染响应数据
                    app.innerHTML = `
                        <h1>${data.hello}</h1>
                        <p>${data.data.name}</p>
                    `;

                    // 渲染列表
                    const ol = document.createElement("ol");
                    data.list.forEach(item => {
                        const li = document.createElement("li");
                        li.textContent = item;
                        ol.append(li);
                    });
                    app.append(ol);
                }
            } catch (err) {
                console.error("请求异常:", err);
            }
        }

        fetchData();
    </script>
</body>
</html>

简化写法

const url = "/get1";

fetch(url)
    .then(response => {
        if (!response.ok) throw new Error(`HTTP error: ${response.status}`);
        return response.json();
    })
    .then(data => console.log("数据:", data))
    .catch(err => console.error("请求失败:", err));

POST 请求

完整示例

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>POST 请求示例</title>
</head>
<body>
    <form id="login">
        <input id="name" placeholder="用户名">
        <hr>
        <input id="passwd" type="password" placeholder="密码">
        <hr>
        <button type="button">登录</button>
    </form>
    <script>
        const url = "/post_demo";
        const button = document.getElementById("button");

        async function login() {
            const name = document.getElementById("name").value;
            const passwd = document.getElementById("passwd").value;

            const response = await fetch(url, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ name, passwd })
            });

            if (response.ok) {
                const data = await response.json();
                console.log(data.name);
            }
        }

        button.onclick = login;
    </script>
</body>
</html>

简化写法

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);
};

请求对比

方法 特点 适用场景
GET 参数在 URL 中 查询、获取数据
POST 参数在 body 中 登录、提交数据

事件处理

事件处理让网页具有交互性,常见事件包括点击、输入、定时等。

DOM 事件与定时器

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>事件处理演示</title>
</head>
<body>
    <div id="btn"><h1>按钮 1</h1></div>
    <div id="btn2"><h1>按钮 2</h1></div>
    <div id="stop"><h1>停止定时器</h1></div>

    <script>
        // 方式一:addEventListener 绑定
        const btn = document.getElementById("btn");
        btn.addEventListener("click", () => console.log("按钮1被点击"));

        // 方式二:onclick 属性
        const btn2 = document.getElementById("btn2");
        function btnf2() {
            console.log("按钮2被点击");
        }
        btn2.onclick = btnf2;

        // 定时循环任务
        const timer = setInterval(() => console.log("每秒执行一次"), 1000);
        const timer2 = setInterval(() => console.log("每0.5秒执行"), 500);

        // 停止与延迟
        const stopBtn = document.getElementById("stop");
        stopBtn.addEventListener("click", () => {
            clearInterval(timer);
            clearInterval(timer2);
            setTimeout(() => console.log("3秒后执行"), 3000);
        });
    </script>
</body>
</html>

常用定时器函数

函数 说明
setInterval(fn, ms) 重复执行,间隔 ms 毫秒
setTimeout(fn, ms) 延迟 ms 毫秒后执行一次
clearInterval() 停止重复执行
clearTimeout() 取消延迟执行

完整综合示例

下面是一个包含登录、数据请求、页面更新的完整演示:

<!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>
        // 获取元素
        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);
        });

        // 模拟登录请求
        function login(username, password) {
            mockRequest({ username, password })
                .then(res => onLoginSuccess(res));
        }

        // 登录成功处理
        function onLoginSuccess(data) {
            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>

总结

JavaScript 三板斧核心要点:

  1. DOM 操作:使用 getElementByIdquerySelectorAll 获取元素,通过 createElementappend 创建元素
  2. 网络请求fetch API 支持 GET(URL 参数)和 POST(JSON body)两种方式
  3. 事件处理addEventListener 绑定事件,setInterval / setTimeout 处理定时任务

掌握这三个技能,就可以完成大多数前端交互需求。