简体   繁体   English

将 select 选项的值设置为 select JSON 数据

[英]Set value on select options to select JSON data

I'm creating a select based on the JSON I got with an API.我正在创建一个基于 JSON 的 select,我使用 API。 Based on that select, when I choose another option I want some data to change (text and image src).基于该 select,当我选择另一个选项时,我希望更改一些数据(文本和图像 src)。

I got the select with the options done.我得到了 select 并完成了选项。 Each option is a name and I done that with forEach.每个选项都是一个名称,我使用 forEach 完成了它。 My problem is setting the value so I can use it to change the other data.我的问题是设置值,以便我可以使用它来更改其他数据。 In my mind the easiest solution would be setting the value to the objects index so when I choose the first option I get 0 and can get the first JSON object.在我看来,最简单的解决方案是将值设置为对象索引,因此当我选择第一个选项时,我得到 0 并且可以获得第一个 JSON object。 I'm not sure if this is the best way anyway.我不确定这是否是最好的方法。

This is my code reduced to only the forEach:这是我的代码减少到只有 forEach:

 <select name="select" id="selector"> </select>
  data_json.show.forEach((element) => {
    document.getElementById('selector').innerHTML +=
    `<option value="">${element.name}</option>`;
  });

(the value is what I want to be the same as the index of each json data) (这个值就是我想和每个json数据的索引一样)

My idea of what I want to get:我对我想要得到的东西的想法:

  <select name="select" id="selector">
    <option value="0">Name_01</option>
    <option value="1">Name_02</option>
    <option value="2">Name_03</option>
  </select>

So I can use the value like this:所以我可以使用这样的值:

  let titulos = document.getElementById("titulos");

  selectVal.onchange = function() {
        let actualVal = selectVal.options[selectVal.selectedIndex].value;
        titulos.innerHTML = "Títulos:" + " " + data_json.show[actualVal].image;;
    };
  <p id="titulos">Títulos:</p>

Hope it makes sense希望有意义

You're setting them all to an empty value.您将它们全部设置为空值。 You can use the array index to give them each a different value.您可以使用数组索引为它们各自赋予不同的值。

  data_json.show.forEach((element, index) => {
    document.getElementById('selector').innerHTML +=
    `<option value="${index+1}">${element.name}</option>`;
  });

BTW, you can simplify selectVal.options[selectVal.selectedIndex].value to just selectVal.value .顺便说一句,您可以将selectVal.options[selectVal.selectedIndex].value简化为selectVal.value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM