You need to enable JavaScript to run this app. 如何使用JavaScript插入并获取动态创建input的值并展示到动态label中
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript插入并获取动态创建input的值并展示到动态label中

问题根因

你原有代码存在3个核心问题:

  1. 点击Add按钮生成输入框时立即取值,此时用户还未输入内容,拿到的只能是空值
  2. 动态生成的输入框没有绑定正确的输入监听事件,无法在用户输入时触发同步逻辑
  3. 输入框和第三列的label没有对应索引,无法做到输入和展示的位置一一匹配

修正后完整代码

HTML代码

<div class="row">
    <div class="column">
        <h2>Column 1</h2>
        <div>
            <input type="radio" value="1" name="col1" id="r1"><label for="r1">1</label>
            <input type="radio" value="2" name="col1" id="r2"><label for="r2">2</label>
            <input type="radio" value="3" name="col1" id="r3"><label for="r3">3</label>
            <input type="radio" value="4" name="col1" id="r4"><label for="r4">4</label>
            <input type="radio" value="5" name="col1" id="r5"><label for="r5">5</label>
        </div>
        <button type="button">Add</button>
    </div>
    <div class="column" style="background-color:#ccc;">
        <h2>Column 2</h2>
        <div class="add-input"></div>
    </div>
    <div class="column">
        <h2>Column 3</h2>
        <div class="add-label"></div>
    </div>
</div>

CSS代码

.column {
    float: left;
    width: 30%;
    padding: 10px;
}
.row:after {
    content: "";
    display: table;
    clear: both;
}

JS代码

const inputDiv = document.querySelector(".add-input");
const labelDiv = document.querySelector(".add-label");
const btn = document.querySelector('button[type="button"]');

// 事件委托监听所有动态生成输入框的输入事件
inputDiv.addEventListener('input', function(e) {
    if (e.target.tagName === 'INPUT' && e.target.name === 'col2') {
        const index = e.target.dataset.index;
        const targetLabel = labelDiv.querySelector(`label[data-index="${index}"]`);
        if (targetLabel) {
            targetLabel.textContent = `Label ${index} - ${e.target.value}`;
        }
    }
})

btn.onclick = function () {
    // 清空历史内容避免重复叠加
    inputDiv.innerHTML = '';
    labelDiv.innerHTML = '';
    
    const checkedRadio = document.querySelector('input[type="radio"]:checked');
    if (!checkedRadio) return;
    const count = Number(checkedRadio.value);
    
    for (let i = 0; i < count; i++) {
        // 生成带索引标记的输入框
        inputDiv.innerHTML += `<input type="text" data-index="${i}" value="" name="col2"><br><br>`;
        // 生成对应索引的占位label
        labelDiv.innerHTML += `<label data-index="${i}">Label ${i} - </label><br><br>`;
    }
};

实现逻辑说明

  • 点击Add按钮时,先清空两列的历史内容,再根据选中的单选值生成对应数量的输入框和占位label,二者通过data-index属性一一绑定
  • 采用事件委托监听第二列所有输入框的输入动作,输入时根据索引找到第三列对应的label,实时更新内容
  • 修复了原有单选label点击不生效、输入事件绑定错误的问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 04:36:02