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

如何用JavaScript遍历JSON文件并在HTML动态生成问答输入框

问题描述

我有一个由用户输入生成的JSON文件,条目数量不固定。希望在JavaScript函数中遍历该JSON的所有条目,并在HTML中逐行显示为问答对。

示例JSON文件:

{
  "What is your name": "Jason", 
  "What is your favorite color": "Blue",
  "When is your birthday?": "Jan 15"
}

点击HTML中的特定按钮后,JSON的每个条目需对应一组问答输入框:问题显示在question输入框,答案显示在answer输入框。条目数量可变,无法预先创建固定数量的输入组。我的HTML代码如下:

<input id="open-btn" class="right-button" value="加载问答" />
<form class="form-container" action="mailto:?subject=Answers" method="post" enctype="text/plain">

  <!-- 想要循环生成的问答输入组 -->
  <div class="form-group">
       <label for="question1">Question </label>
       <input type="text" id="question1" class="form-input" name="Question1">
  </div>
  <div class="form-group">
       <label for="answer1">Answer </label>
       <input type="text" id="answer1" class="form-input" name="Answer1">
  </div>

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

目前我的JavaScript代码仅能显示JSON的第一个条目,无法动态生成对应数量的输入组:

const open = document.getElementById("open-btn");

open.addEventListener('click', () => {
    $.getJSON("../static/data.json", function(data) {
        $.each(data, function (key, value) {
            document.getElementById("question1").value = key
            document.getElementById("answer1").value = value     
        })
        console.log("Log Data:",data)
    });
});

请问如何实现遍历JSON所有条目并动态生成对应数量的HTML问答输入框?或能否将JSON数据存入JS变量后在HTML循环中使用?


解决方案

步骤1:调整HTML结构,添加动态容器

先把原有的固定输入组替换成一个空容器,专门用来存放动态生成的问答组:

<input id="open-btn" class="right-button" value="加载问答" />
<form class="form-container" action="mailto:?subject=Answers" method="post" enctype="text/plain">

  <!-- 新增容器,用于动态生成问答输入组 -->
  <div id="qa-container"></div>

  <button type="submit" class="btn btn-primary">Submit</button>
</form>

步骤2:编写动态生成逻辑

核心思路是遍历JSON的每个键值对,为每一对创建对应的HTML元素,再添加到容器中。下面提供原生JS和jQuery两种实现方式:

原生JS版本

const openBtn = document.getElementById("open-btn");
const qaContainer = document.getElementById("qa-container");

openBtn.addEventListener('click', () => {
    // 清空容器,避免重复加载
    qaContainer.innerHTML = '';

    // 加载JSON文件
    fetch("../static/data.json")
        .then(res => res.json())
        .then(data => {
            let index = 1;
            // 遍历所有问答对
            for (const [question, answer] of Object.entries(data)) {
                // 创建问题输入组
                const questionGroup = document.createElement('div');
                questionGroup.className = 'form-group';
                
                const questionLabel = document.createElement('label');
                questionLabel.setAttribute('for', `question${index}`);
                questionLabel.textContent = 'Question ';
                
                const questionInput = document.createElement('input');
                questionInput.type = 'text';
                questionInput.id = `question${index}`;
                questionInput.className = 'form-input';
                questionInput.name = `Question${index}`;
                questionInput.value = question;

                questionGroup.append(questionLabel, questionInput);
                qaContainer.appendChild(questionGroup);

                // 创建答案输入组
                const answerGroup = document.createElement('div');
                answerGroup.className = 'form-group';
                
                const answerLabel = document.createElement('label');
                answerLabel.setAttribute('for', `answer${index}`);
                answerLabel.textContent = 'Answer ';
                
                const answerInput = document.createElement('input');
                answerInput.type = 'text';
                answerInput.id = `answer${index}`;
                answerInput.className = 'form-input';
                answerInput.name = `Answer${index}`;
                answerInput.value = answer;

                answerGroup.append(answerLabel, answerInput);
                qaContainer.appendChild(answerGroup);

                index++;
            }
        })
        .catch(err => console.error('加载JSON失败:', err));
});

jQuery版本(适合习惯用jQuery的场景)

const openBtn = $('#open-btn');
const qaContainer = $('#qa-container');

openBtn.on('click', () => {
    // 清空容器
    qaContainer.empty();

    // 加载JSON并生成输入组
    $.getJSON("../static/data.json", function(data) {
        let index = 1;
        $.each(data, function(question, answer) {
            // 拼接问题输入组HTML
            const questionHtml = `
                <div class="form-group">
                    <label for="question${index}">Question </label>
                    <input type="text" id="question${index}" class="form-input" name="Question${index}" value="${question}">
                </div>
            `;
            // 拼接答案输入组HTML
            const answerHtml = `
                <div class="form-group">
                    <label for="answer${index}">Answer </label>
                    <input type="text" id="answer${index}" class="form-input" name="Answer${index}" value="${answer}">
                </div>
            `;
            // 添加到容器
            qaContainer.append(questionHtml).append(answerHtml);
            index++;
        });
    }).fail(function(err) {
        console.error('加载JSON失败:', err);
    });
});

关键细节说明

  1. 清空容器:每次点击按钮时先清空容器,防止重复生成输入组。
  2. 唯一标识:用索引值为每个输入框生成唯一的id和name,确保表单提交时参数不冲突。
  3. 遍历逻辑:通过Object.entries()(原生JS)或$.each()(jQuery)遍历JSON对象的所有键值对,将键作为问题、值作为答案填充到输入框中。

关于“JSON数据存入JS变量后在HTML循环中使用”

如果是纯前端静态页面,只能通过JavaScript动态生成HTML——上面的方案已经实现了这一点:先把JSON加载到JS变量,再循环生成对应的输入组。如果是服务器端渲染场景(比如用EJS、Handlebars等模板引擎),可以把JSON传入模板后用模板语法直接循环生成,但静态页面无法直接在HTML中写循环逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:20:23