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

如何获取导航栏输入框值并通过fetch加载对应JSON文件

解决输入框初始化取值异常与JSON加载问题

问题场景

需要获取导航栏内id为examples的输入框的值,通过fetch加载对应路径的JSON文件。点击标签内的#1、#2按钮,会调用setExampleValue函数将输入框值设为example1或example2,但当前页面初始化时直接取值的代码无法获取选中的example2,console.log(fid)输出不符合预期,导致无法正常加载目标JSON文件。

核心代码

HTML结构

<input id="examples" class="input" name="examples" placeholder=" " />
<label for="examples" class="placeholder">
    Examples
    <span id="example1" class="example" onclick="setExampleValue('example1')"> #1</span>
    <span id="example2" class="example" onclick="setExampleValue('example2')"> #2</span>
</label>

当前取值代码

const fid = document.getElementById("examples").value;
console.log(fid)
const fpath = `/path/${fid}.json`;
fetch(fpath)
    .then(response => response.json())
    .then( data => {
        var  x = data.x
    })

解决方案

  1. 给输入框设置默认值
    页面初始化时输入框默认是空值,直接取值自然拿不到example2。给input标签添加value属性,指定默认选中的示例值:
<input id="examples" class="input" name="examples" placeholder=" " value="example2" />
  1. 封装加载逻辑并修正触发时机
    原代码只在页面加载时执行一次,且可能在DOM未完全加载完成时就运行,同时点击按钮后不会重新触发JSON加载。把取值和fetch逻辑封装成函数,在DOM初始化完成和按钮点击时分别调用:
// 封装JSON加载逻辑
function loadExampleJSON() {
  const fid = document.getElementById("examples").value;
  console.log(fid);
  const fpath = `/path/${fid}.json`;
  fetch(fpath)
    .then(response => {
      if (!response.ok) throw new Error("请求失败");
      return response.json();
    })
    .then(data => {
      var x = data.x;
      // 在这里添加数据处理、渲染等逻辑
    })
    .catch(err => console.error("JSON加载失败:", err));
}

// DOM完全加载后执行初始化加载
window.addEventListener('DOMContentLoaded', loadExampleJSON);

// 修改setExampleValue,设置值后立即触发加载
function setExampleValue(value) {
  document.getElementById("examples").value = value;
  loadExampleJSON();
}
  1. 关键问题说明
  • 原代码执行时机可能过早:如果代码放在<head>中,此时input元素还未被渲染,取值会得到undefined;
  • 未监听按钮点击后的状态变化:点击按钮修改输入框值后,原代码不会重新执行fetch,只有初始化的一次请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:34:56