首页 > 解决方案 > 根据选定的“选项”更改 innerHTML 结果

问题描述

当我从下拉菜单中选择一个选项时,我试图拥有它,它将使用 data.json 文件中的正确信息更新结果。现在它将从 data[0] 返回字符串化数据,但我希望它根据所选选项 id 返回。因此,如果用户选择“Sarah”,即选项 id="4",我希望它从第 4 个 JSON 对象中获取数据。

<select id="options" onchange="myfunction()">
    <option ></option>
    <option id="0">Tyson</option>
    <option id="1">Jessica</option>
    <option id="2">Joshua</option>
    <option id="3">Jennifer</option>
    <option id="4">Sarah</option>
</select>
<br><br>

<div id="myData"></div>
function myfunction() {
    fetch('data.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            appendData(data);
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });
    function appendData(data) {
        var mainContainer = document.getElementById("myData");

        var div = document.createElement("div");
        div.innerHTML = JSON.stringify(data[0], null, 4);
        mainContainer.appendChild(div);
    }
}
[
  {
  "id" : 0,
  "first_name": "Tyson",
  "gender": "male",
  "isAlive": true,
  "married": true,
  "has_children": false,
  },

  {
  "id" : 1,
  "first_name": "Jessica",
  "gender": "female",
  "isAlive": true,
  "married": true,
  "has_children": false,
  },
  {
    "id" : 2,
    "first_name": "Joshua",
    "gender": "male",
    "isAlive": true,
    "married": true,
    "has_children": true,
  },

  {
    "id" : 3,
    "first_name": "Jennifer",
    "gender": "female",
    "isAlive": true,
    "married": true,
    "has_children": true,
 },
  {
    "id" : 4,
    "first_name": "Sarah",
    "gender": "female",
    "isAlive": true,
    "married": false,
    "has_children": false,
  }

标签: javascripthtmljson

解决方案


首先,appendData搬出myfunction。它不需要嵌套。

其次,您需要在 中捕获下拉列表的选定值myfunction,然后data根据该值过滤您的集合。像这样的东西,也许:

function myfunction() {
    var selectedId = document.getElementById("options").value; // e.g. "4" (string)
    fetch('data.json')
        .then(function (response) {
            return response.json();
        })
        .then(function (data) {
            // let's filter the data
            var person = data.filter(function(p) { return p.id == selectedId; });
            appendData(person);
        })
        .catch(function (err) {
            console.log('error: ' + err);
        });
}

最后,您必须稍微调整您的appendData函数以不再尝试索引该data对象,因为它不再是一个数组:

function appendData(data) {
    var mainContainer = document.getElementById("myData");

    var div = document.createElement("div");
    div.innerHTML = JSON.stringify(data, null, 4);
    mainContainer.appendChild(div);
}

最后一个建议是不要将事件放在您的 HTML 属性中。这是非常过时的。相反,学习如何使用addEventListener.


推荐阅读