简体   繁体   English

使用JSON数据在HTML中填充下拉列表

[英]Populate drop-down list in HTML using JSON data

I'm a student and very new to code. 我是一名学生,对代码非常陌生。 I've created a drop-down list using HTML and CSS, and I'm trying to populate it using data from JSON. 我使用HTML和CSS创建了一个下拉列表,并尝试使用JSON中的数据填充该列表。 This is my HTML code: 这是我的HTML代码:

    <div class="dropdown">
  <button class="dropbtn">Choose your area</button>
  <div class="dropdown-content">
    <a href="#">Place 1</a>
    <a href="#">Place 2</a>
    <a href="#">Place 3</a>

  </div>
</div>

I'm trying to replace 'Place 1', 'Place 2' etc with about 150 real place names. 我正在尝试将“ Place 1”,“ Place 2”等替换为大约150个真实的地名。 These are in JSON: 这些在JSON中:

    "areaNames": [
 {
   "A": 1,
   "B": "Barking & Dagenham"
 },
 {
   "A": 2,
   "B": "Barnet"
 },

and so on. 等等。 How do I pull in the place names from JSON to be in the place of 'Place 1', 'Place 2' etc? 如何从JSON中提取地名,以使其位于“ Place 1”,“ Place 2”等位置? I've tried following the advice in response to similar tutorials but that seems to give me a list of several separate drop-down boxes rather than a simple list of places. 我已经尝试按照建议来响应类似的教程,但这似乎给了我几个单独的下拉框的列表,而不是简单的位置列表。

Thanks for your help. 谢谢你的帮助。

Here is working example with pure JS. 这是纯JS的工作示例。

 var areaNames = [ { "A": 1, "B": "Barking & Dagenham", "C": "https://google.com" }, { "A": 2, "B": "Barnet", "C": "https://google.com" } ] var dropdownContent = document.querySelector('.dropdown-content'); for (i = 0; i < areaNames.length; i++) { var element = areaNames[i]; var htmlToAppend = document.createElement('a'); htmlToAppend.innerHTML = element.B; htmlToAppend.href = element.C; dropdownContent.appendChild(htmlToAppend); } 
 a { display: block; } 
 <div class="dropdown"> <button class="dropbtn">Choose your area</button> <div class="dropdown-content"> </div> </div> 

I don't see a dropdown in the code. 我没有在代码中看到下拉菜单。

You could use jQuery , which is a Javascript library, to accomplish your goal. 您可以使用jQuery (这是一个Javascript库)来实现您的目标。

HTML: HTML:

<select id="sel">

</select>

JavaScript: JavaScript:

$(function() {
    var data = [
        {
        "id": "1",
        "name": "test1"},
    {
        "id": "2",
        "name": "test2"}
    ];
    $.each(data, function(i, option) {
        $('#sel').append($('<option/>').attr("value", option.id).text(option.name));
    });
})

I believe you have already loaded the JSON data in the DOM so you can access the data in your javascript. 我相信您已经在DOM中加载了JSON数据,因此可以访问JavaScript中的数据。 Are you using any javascript library or framework like - jQuery, AngularJS or plain Javascript? 您是否在使用任何JavaScript库或框架,例如jQuery,AngularJS或纯Javascript? It is always better to organize your javascript code externally in a file with extension .js and load it in your HTML using <script> tag within <head> or <body> section. 最好将外部的javascript代码组织在扩展名为.js的文件中,并使用<head><body>部分中的<script>标记将其加载到HTML中。

Steps to generate the anchor tags dynamically in an HTML: 在HTML中动态生成定位标记的步骤:

  1. Get the Data from JSON into the DOM object (javascript) 将数据从JSON获取到DOM对象(javascript)
  2. Create/track the parent HTML element which will contain the options. 创建/跟踪将包含选项的父HTML元素。 Keep this reference in a variable. 将此引用保留在变量中。
  3. Iterate into the data array (or objects) accessed from the JSON 迭代到从JSON访问的数据数组(或对象)中
  4. Get the value of the relevant property within each iteration 获取每次迭代中相关属性的值
  5. Create the HTML element that will be repeatedly used with each data value. 创建将与每个数据值重复使用的HTML元素。 In this case the template should be 'value' 在这种情况下,模板应为“值”
  6. Append this generated code into the parent element that was stored in #2 above. 将此生成的代码附加到上面#2中存储的父元素中。
  7. After the iteration is complete, inject (append) the parent element into the DOM at the appropriate place. 迭代完成后,在适当的位置将父元素注入(附加)到DOM中。

Case 1: Plain javascript - 情况1:纯JavaScript-

Use XHR to read the JSON and get the data into a variable. 使用XHR读取JSON并将数据放入变量中。 Lets name it JSONData. 让我们将其命名为JSONData。

We will keep the reference of the parent element created in the HTML within javascript. 我们将保留在javascript中HTML中创建的父元素的引用。

//hoping that you have only one element with this classname or the //希望您只有一个元素与此类名或

//concerned element is the first element by this classname in this HTML code. //有关的元素是此HTML代码中此类名称的第一个元素。

//Generally, as a good practice we should either use ID to identify an element individually within our javascript code, ///通常,作为一种好的做法,我们应该使用ID来在我们的javascript代码中分别标识一个元素,

//else use specific identifiers for the same. //否则使用特定的标识符。

var parentDropdownContainer = document.getElementsByClassName('dropdown-content')[0]; var parentDropdownContainer = document.getElementsByClassName('dropdown-content')[0];

Iterating in the JSON data 迭代JSON数据

for (var counter = 0, len = JSONData.length - 1; counter < len; counter ++){
  //we will add logic to generate HTML
}

You can use the other variants of the iteration - for in, while, Array.splice(), etc upto your understanding. 您可以使用迭代的其他变体-用于Array.splice()等,直到您理解为止。

Within this iterator we need to create a HTML code and append it to the parent container 在此迭代器中,我们需要创建一个HTML代码并将其附加到父容器中

for (var counter = 0, len = JSONData.length - 1; counter < len; counter ++){
  var currentData = JSONData[counter]; //this holds the reference of the current data in this iteration
  var dropdownElement = document.createElement('a');
  dropdownElement.setAttribute('href','#'); //this adds the href attribute into the anchor element.
  //lets add another attribute to the anchor element to represent the dynamic id/value associated with this data
  dropdownElement.setAttribute('data-value',currentData.A);
  //lets add the value inside the anchor element
  dropdownElement.innerHTML = currentData.B;
  //lets append this element to the parent container
  parentDropdownContainer.appendChild(dropdownElement);
}

Now this should render the required dynamic options in the dropdown. 现在,这应该在下拉菜单中呈现所需的动态选项。

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

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