You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用document.getElementById()无法打印输入框值的技术问题

问题解决:点击按钮无法打印输入框值到控制台

问题原因

  1. 变量初始化时机错误:页面加载时就获取了输入框的值,此时输入框为空,xum和bioma一直是空字符串,点击按钮时打印的是初始空值。
  2. 表单默认提交行为:按钮为type="submit",点击后触发表单提交,页面刷新导致控制台输出瞬间被清空,看起来像是没有输出。

修复后的代码

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 修正viewpoint拼写错误 -->
        <title>Cálculadora C.O.C</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <header>
            <h2 class="logo">C.O.C</h2>
            <nav class="navigation">
                <a href="#"></a>
                <a href="#"></a>
                <a href="#"></a>
                <a href="#"></a>
                <button class="btnLogin-popup">Calculadora</button>
            </nav>
        </header>

        <div class="wrapper">
            <div class="form-box login">
                    <h2>C.O.C</h2>
                    <form action="#">
                        <div class="input-box">
                            <span class="icon"><ion-icon name="leaf-outline"></ion-icon></span>
                            <input id="area" required>
                        </div>
                        <div class="input-box">
                            <span class="icon"><ion-icon name="earth-outline"></ion-icon></span>
                            <input id="bioma" type="text" required> <!-- 修正type="Bioma"为合法的text类型 -->
                        </div>
                    <button type="submit" class="btn" onclick="teste(event)">Calcular</button>
            </div>
        </div>
        <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>
<script>
    function teste(event){
        // 阻止表单默认提交行为,避免页面刷新
        event.preventDefault();
        // 每次点击时获取当前输入框的最新值
        var xum = document.getElementById("area").value;
        var bioma = document.getElementById("bioma").value;
        console.log(xum);
        console.log(bioma);
    }
</script>
</body>
</html>

关键修改点

  • 将获取输入框值的代码移到teste()函数内部,确保每次点击按钮时获取最新输入内容。
  • 添加event.preventDefault()阻止表单提交导致的页面刷新。
  • 修正两处细节错误:meta标签的viewpoint拼写为viewport;bioma输入框的type改为合法的text类型。

内容的提问来源于stack exchange,提问作者Edu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:47:50