我正在尝试弄清楚当行项目遇到按钮单击时传递的一个或多个变量时如何选择特定的 JSON 对象。 到目前为止,我让它工作,但它说[对象],[对象]。 我相信这是因为它是在数组中返回的。 我错过了什么?
var Type = "Champagne";
$(document).ready(function(){
$("button").click(function(){
$("#data-details").empty();
$.get("working-data-file.json",{Type: Type},function(result){
$.each(result.data, function(i, field){
$("#data-details").append(this.objects.Title);
});
});
});
});
这。JSON 文件如下所示:
{"objects":
[
{
"Type": "Champagne",
"Sweetness": "Brut",
"Producer": "Dom Perignon",
"Vintage": "2006",
"Recommendation": "Classic",
"Data": "12.29.2012",
"Title": "The wine’s opulence – contained and succulent, round at heart – reveals itself in the mouth."
},
{
"Type": "Cava",
"Sweetness": "Brut-Nature",
"Producer": "Canals Canals",
"Vintage": "2014",
"Recommendation": "Preferred",
"Data": "12.29.2012",
"Title": "2nd Cava."
}
]
}
你可以用jquery循环
。
$( document ).ready(function() {
$('#button').click(function(e){
$.each(data.objects, function( i, item) {
$("#data-details").append('<p>' + item.Title + '</p>');
});
})
});
var data = {"objects":
[
{
"Type": "Champagne",
"Sweetness": "Brut",
"Producer": "Dom Perignon",
"Vintage": "2006",
"Recommendation": "Classic",
"Data": "12.29.2012",
"Title": "The wine’s opulence – contained and succulent, round at heart – reveals itself in the mouth."
},
{
"Type": "Cava",
"Sweetness": "Brut-Nature",
"Producer": "Canals Canals",
"Vintage": "2014",
"Recommendation": "Preferred",
"Data": "12.29.2012",
"Title": "2nd Cava."
}
]
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=button id="button" value="click me"/>
<div id="data-details"></div>
尝试:
var result={"objects":
[
{
"Type": "Champagne",
"Sweetness": "Brut",
"Producer": "Dom Perignon",
"Vintage": "2006",
"Recommendation": "Classic",
"Data": "12.29.2012",
"Title": "The wine’s opulence – contained and succulent, round at heart – reveals itself in the mouth."
},
{
"Type": "Cava",
"Sweetness": "Brut-Nature",
"Producer": "Canals Canals",
"Vintage": "2014",
"Recommendation": "Preferred",
"Data": "12.29.2012",
"Title": "2nd Cava."
}
]
}
Object.keys(result).forEach(key => {
let value = result[key];
console.log(value[0].Title);
})
[键]})