如何使用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"] } ]
答案 0 :(得分:0)
即使没有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('');