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

点击加号按钮后输入框值获取异常,控制台持续输出‘prod’

点击按钮后无法获取输入框最新值的问题解决

你遇到的问题是点击加号按钮后,控制台始终输出输入框的旧值(比如“prod”),这是代码逻辑问题,和浏览器无关。

问题代码分析

你的JS代码中,inputValue = userInput.value在页面加载时就执行了,只会捕获输入框的初始值。之后输入框内容变化时,这个变量不会自动更新,所以点击按钮时打印的还是一开始存储的旧值。

原代码

HTML

<!DOCTYPE html>
<html lang="en">
<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">
  <title>Document</title>
</head>
<body>
  
  <input type="text">
  <button id="add-btn">+</button>

  <h1>List</h1>
  <ol>
    <li>
      <p>Coffee</p><button id="remove-btn">-</button>
    </li>
  </ol>

  <script src="script.js"></script>
</body>
</html>

CSS

li {
  display: flex;
  align-items: center;
}

li button {
  height: 20px;
  margin-left: 20px;
}

JS

let userInput = document.querySelector('input')
let inputValue = userInput.value

let addItemBtn = document.getElementById('add-btn')

let newLi = "Hi, Im Li"

addItemBtn.addEventListener('click', (event) => {
  if (event.target === addItemBtn) {
    console.log("inputValue: ", inputValue);    
  }
})

解决方案

把获取输入框值的操作放到点击事件的回调函数内部,这样每次点击按钮时都会实时读取输入框的当前内容:

修改后的JS代码

let userInput = document.querySelector('input')
let addItemBtn = document.getElementById('add-btn')

let newLi = "Hi, Im Li"

addItemBtn.addEventListener('click', (event) => {
  if (event.target === addItemBtn) {
    // 每次点击时获取最新的输入值
    const inputValue = userInput.value
    console.log("inputValue: ", inputValue);    
  }
})

或者更简洁的写法,直接在打印时读取:

addItemBtn.addEventListener('click', (event) => {
  if (event.target === addItemBtn) {
    console.log("inputValue: ", userInput.value);    
  }
})

这样修改后,点击按钮就能正确输出输入框的最新内容了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:25:34