将map连接到json文件进行循环

connecting map to json files for loop

本文关键字:循环 文件 json map 连接      更新时间:2023-09-26

这可能是一个非常简单的问题,但我似乎在任何地方都找不到答案或解释。

如何以及在何处连接地图(图像文件来自何处)对于我在JSON中放置的图像和名称,对于需要在浏览器窗口中显示的图像。我对JSON、循环和JS都很陌生。

这是我的代码,如果你需要查看它,了解我是如何制作的。

JSON;

{ "main_object": {
    "imagesJ": ["beak", "cat", "egg", "meel", "milk", "passport", "spoon", "thee"],
    "woorden": ["words", "not", "needed", "yet"]
 }
}

//JavaScript
var jsonData = "noJson";
var hr = new XMLHttpRequest();
$(document).ready(function() {
  var jsonData = 'empty';
  $.ajax({
    async: false,
    url: "./js/data.json",
    dataType: 'html',
    success: function(response) {
      jsonData = JSON.parse(response);
      console.log('ok');
      imagesJ = jsonData.main_object.imagesJ;
      woorden = jsonData.main_object.woorden;
      for (i = 0; i < imagesJ.length; i++) {
        imagesJ[i] + '.jpg';
        // => /img/[imagesJ[x]].jpg
      }
    },
    error: function() {
      console.log('JSON could not be loaded.');
    }
  });
  console.log(jsonData);
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Sleepopdracht</title>
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="css/css.css">
</head>
<body>
  <header>
  </header>
  <div class="container" id="container">
    <div class="images" id="images"></div>
  </div>
  <footer>
  </footer>
  <script type="text/javascript" src="js/javascript.js"></script>
</body>
</html>

您想要的是为imagesJ中的每个图像添加一个图像标记。循环的结构很好,可以使用jQuery来append(),使用image标记来div id="images"。for循环看起来像这样:

for (i = 0; i < imagesJ.length; i++) {
    var path = imagesJ[i] + '.jpg';
    $('#images').append('<img id="image' + i + '" src="' + path + '" />');
}

如果我没有错的话,你只需要创建一个"img"元素,设置它的"src"属性并附加到"images"节点;

以下是如何进行

var titles = ["words", "not", "needed", "yet"];
var imagesContainer = document.getElementById('images');
titles.forEach(function(title){
    var img = document.createElement('img');
    img.src = '/img/' + title + '.jpg';
    imagesContainer.appendChild(img);
});

示例:https://jsfiddle.net/vbesoc75/

编辑

具体示例:

$.ajax({
     async: false,
     url: "./js/data.json",
     dataType: 'html',
     success: function(response) {
       jsonData = JSON.parse(response);
       console.log('ok');
       imagesJ = jsonData.main_object.imagesJ;
       woorden = jsonData.main_object.woorden;
       var imagesContainer = document.getElementById('images');
       for (i = 0; i < imagesJ.length; i++) {
         var img = document.createElement('img')
         img.src = '/img/' + imagesJ[i];
         imagesContainer.appendChild(img);
       }
    },