检索 JSON 并输出到复选框

问题描述 投票:0回答:2

我目前正在从 PowerShell 脚本检索此类 JSON 数据:

[{"Name":"grp_SIR_RW"},{"Name":"grp_SIR_R"},{"Name":"grp_SPIE_RW"},{"Name":"grp_GOR_R"}]

我需要检索此输出中的每个名称并将它们粘贴到 HTML 复选框中,以便我的用户可以选择其中一个或多个名称,并且显示需要良好组织,因为我可以显示大约 30 个组。

javascript html json scripting
2个回答
0
投票

您需要从 json 动态创建复选框

const data = [{
    "Name": "grp_SIR_RW"
  },
  {
    "Name": "grp_SIR_R"
  },
  {
    "Name": "grp_SPIE_RW"
  },
  {
    "Name": "grp_GOR_R"
  }
]
// creating a fragment to hold the dynamically created checkbox
// and it will be used to project the elements to the main 
//container
const temp = document.createElement('template')

data.forEach((item) => {
  const label = document.createElement('label');
  label.setAttribute('for', item.Name);
  label.textContent = item.Name;
  const check = document.createElement('input');
  check.setAttribute('type', 'checkbox')
  check.id = item.Name;
  // appending the created elements to the fragment
  temp.content.appendChild(label);
  temp.content.appendChild(check);
});


const clone2 = temp.content.cloneNode(true);
document.getElementById('checkBoxContainer').appendChild(clone2)
<div id="checkBoxContainer">

</div>


0
投票

我假设您问的是如何在 HTML 中显示已经从数据源检索到的 JSON 数据,在这种情况下,请尝试以下操作

在 HTML 中为复选框创建占位符

<div id="checkboxContainer">
    <!-- Place to create the checkboxes -->
</div>

接下来数据必须动态插入到 HTML 占位符中,因此请在 JS 中尝试以下操作,假设您已经检索了数据。

const jsonData = [{ "Name": "grp_SIR_RW" }, { "Name": "grp_SIR_R" }, { "Name": "grp_SPIE_RW" }, { "Name": "grp_GOR_R" }];

const generateCheckboxes = async (data) => {
    var container = document.getElementById('checkboxContainer');

    data.forEach(function (item) {
        var checkbox = document.createElement('input');
        checkbox.type = 'checkbox';
        checkbox.name = 'group';
        checkbox.value = item.Name;

        var label = document.createElement('label');
        label.appendChild(checkbox);
        label.appendChild(document.createTextNode(item.Name));

        container.appendChild(label);
    });
}

接下来必须触发此函数,因此假设您有一个函数来获取数据,一旦获取了数据,就调用该函数并将数据传递给该函数。

await generateCheckboxes(jsonData);
© www.soinside.com 2019 - 2024. All rights reserved.