gpt4 book ai didi

javascript - 将 map 连接到 json 文件 for 循环

转载 作者:行者123 更新时间:2023-12-02 14:50:45 25 4
gpt4 key购买 nike

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

如何以及在哪里连接 map (图像文件来自哪里)对于我放置在 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>

最佳答案

听起来您想要的是添加 image tag对于 imagesJ 中的每个图像。您的循环结构对此很有好处,您可以使用 jQuery to append()将图像标签添加到div id="images"。 for 循环看起来像这样:

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

关于javascript - 将 map 连接到 json 文件 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36200328/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com