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

如何将两个输入框的值存入单个数组并通过按钮展示

解决方案

1. 调整HTML结构

先创建两个输入框和对应的存储按钮,再加一个用于展示数组内容的按钮:

<input type="text" id="input1" placeholder="输入内容1">
<button onclick="storeInput('input1')">存入内容1</button>

<input type="text" id="input2" placeholder="输入内容2">
<button onclick="storeInput('input2')">存入内容2</button>

<button onclick="showStoredInputs()">展示所有存入内容</button>
<div id="displayArea"></div> <!-- 用于展示数组内容的容器 -->

2. 修改JavaScript逻辑

让存储函数支持传入输入框ID实现复用,同时新增展示函数:

const storedUserInputs = [];

// 存储指定输入框的内容
function storeInput(inputId) {
  const input = document.getElementById(inputId);
  if (input.value.trim()) { // 可选:过滤空内容
    storedUserInputs.push(input.value.trim());
    input.value = "";
    console.log(storedUserInputs);
  }
}

// 展示数组中的所有内容
function showStoredInputs() {
  const displayArea = document.getElementById("displayArea");
  if (storedUserInputs.length === 0) {
    displayArea.textContent = "暂无存入内容";
    return;
  }
  // 用换行分隔每个元素,也可根据需求改成其他格式展示
  displayArea.textContent = storedUserInputs.join("\n");
}

说明

  • 给每个输入框分配唯一ID,点击对应按钮时把ID传给storeInput函数,函数根据ID获取输入框的值并存入数组
  • 加入空内容过滤,避免存入无效的空字符串(不需要的话可直接删掉if (input.value.trim())判断)
  • 新增的showStoredInputs函数会把数组内容展示到页面的displayArea容器中,也可按需改成弹窗等其他展示形式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 13:57:28