jquery - 使用 AJAX 从 JSON 文件中获取数据。如何使用 jQuery 缩短代码?
问题描述
如何使用 jQuery 缩短代码?而不是手动选择每个元素,也许使用单独的函数来创建<li>
元素可能是一个想法?
$.ajax({
url: 'choosePizza.json',
dataType: 'json',
type: 'GET',
success: function(choosePizzaData) {
choosePizzaHTML(choosePizzaData);
}
});
function choosePizzaHTML(choosePizzaInData) {
var boxar = $('.box1_data');
var text = "";
/*Selecting each parameter manually and get the value from the json file and place them in a list. Is there a way to shorten this? Without having to select it manually*/
$(choosePizzaInData[0]).each(function(index, value) {
text += '<li>' + value.botten[0] + '</li>';
text += '<li>' + value.botten[1] + '</li>';
});
boxar.html(text);
var box2 = $('.box2_data');
var text = "";
$(choosePizzaInData[1]).each(function(index, value) {
text += '<li>' + value.topping[0] + '</li>';
text += '<li>' + value.topping[1] + '</li>';
text += '<li>' + value.topping[2] + '</li>';
});
box2.html(text);
}
示例 JSON:
[ { "botten": ["Krispig", "tunn"] }, { "topping": ["kött", "kyckling", "tomat"] }, { "extra": ["Fanta", "Coca cola", "Sprite"] } ]
解决方案
即使没有 JQuery,您也可以使用 map 方法缩短代码:
text = choosePizzaInData[0].botten.map(function(v) {
return '<li>' + v + '</li>';
}).join('');
text = choosePizzaInData[1].topping.map(function(v) {
return '<li>' + v + '</li>';
}).join('');
推荐阅读
- rust - Rust - 'String' 和 'str' 在内存中有何不同?
- react-native - React Native - onPress 触发错误事件
- node.js - 我如何计算每个类别的考试
- discord.py - Discord bot 不工作,也没有显示任何错误
- laravel-passport - 有一个有趣的问题。我正在使用 Laravel 8,并且从护照中收到此错误:安装命令,我无法解决
- webdriver - ChromeDriver 无法解析为类型
- javascript - TypeError:在运行 npm start 时无法读取反应中未定义的属性“原型”
- java - 试图获取图表的边缘
- fortran - 如何在 do 循环中获取结果以在另一个计算中输入此结果
- r - 为了找到多个 csv 文件中某些行的平均值,我应该怎么做?