Skip to content
js获取地址上面url参数
js
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 假设当前 URL 是:https://example.com/page?name=xiaoji&age=25
        const url = new URL(window.location.href); // 获取当前页面的 URL
        const params = new URLSearchParams(url.search); // 获取查询字符串部分

        // 获取单个参数
        const name = params.get("name"); // 获取 name 参数的值,结果是 "xiaoji"
        const age = params.get("age"); // 获取 age 参数的值,结果是 "25"

        console.log(name, age);

        // 遍历所有参数
        for (const [key, value] of params.entries()) {
            console.log(`${key}: ${value}`);
        }
    </script>
</body>

</html>