You need to enable JavaScript to run this app. 使用原生JS与JSON创建动态单选按钮列表的实现问题
优惠活动
大模型
产品
解决方案
定价
更多

使用原生JS与JSON创建动态单选按钮列表的实现问题

错误点说明
  • 遍历数组错误使用for...in语法,仅能拿到数组索引而非元素对象,同时代码中直接引用未声明的itemID变量,会触发JavaScript运行错误,导致整个脚本执行中断、页面无内容展示。
  • 单选按钮未配置同组name属性,无法实现单选互斥效果。
  • 创建的label元素未插入到DOM结构中,且label的for属性未和单选按钮的id正确关联,无法实现点击文本选中对应单选按钮的交互。
  • 原代码中<form>标签未闭合,属于HTML结构语法错误。
修正后完整代码
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Add inventory item</title>
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  </head>
  <body>
    <header>
    </header>
    <section>
      <form action="" id="input4radio">
      </form>
    </section>
    <script>
    const header = document.querySelector('header');
    const section = document.querySelector('section');
    var inventoryItems = [{"itemID":0,"itemName":"Ammo"},{"itemID":1,"itemName":"Armor"},{"itemID":2,"itemName":"Good"},{"itemID":3,"itemName":"Potion"},{"itemID":4,"itemName":"Ring"},{"itemID":5,"itemName":"Rod"},{"itemID":6,"itemName":"Scroll"},{"itemID":7,"itemName":"Staff"},{"itemID":8,"itemName":"Wand"},{"itemID":9,"itemName":"Weapon"},{"itemID":10,"itemName":"Wondrous Item"}];
    function onLoad() {
      var form = document.getElementById('input4radio');
      // 改用for...of遍历数组元素
      for (let item of inventoryItems) {
        var newRadio = document.createElement('input'); 
        newRadio.type = 'radio';
        // 同组单选设置相同name属性实现互斥
        newRadio.name = 'inventory_item';
        newRadio.id = `item_${item.itemID}`;
        newRadio.value = item.itemName;
        var newLabel = document.createElement('label');
        var t = document.createTextNode(item.itemName);
        // 关联label和对应单选按钮
        newLabel.setAttribute("for", `item_${item.itemID}`);
        newLabel.appendChild(t);
        form.appendChild(newRadio); 
        form.appendChild(newLabel);
        form.appendChild(document.createElement('br'));
      }
    }
    window.onload = onLoad;
    </script>
  </body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 04:00:05