我有一些关于JSON文件的数据。
var data = [{
"gender": "male",
"name": {
"first": "rubween",
"last": "dean"
}
},
{
"gender": "male",
"name": {
"first": "rubween",
"last": "dean"
}
},
{
"gender": "female",
"name": {
"first": "rubenq",
"last": "dean"
}
}, {
"gender": "female",
"name": {
"first": "rubenr",
"last": "dean"
}
}
];

我想仅在HTML div id ='输出'上输出他们的名字gender: male
。使用jQuery或JavaScript
答案 0 :(得分:0)
试试如下。
var data = [{
"gender": "male",
"name": {
"first": "rubween",
"last": "dean"
}
},
{
"gender": "male",
"name": {
"first": "rubween",
"last": "dean"
}
},
{
"gender": "female",
"name": {
"first": "rubenq",
"last": "dean"
}
}, {
"gender": "female",
"name": {
"first": "rubenr",
"last": "dean"
}
}
];
data.forEach(function(person) {
if (person.gender === "male") {
document.getElementById("output").innerHTML += person.name.first + " " + person.name.last + "<br>";
}
});
<div id="output"></div>
答案 1 :(得分:0)
灵感来自:jquery loop on Json data using $.each
var obj = [{
"gender": "male",
"name": {
"first": "rubween",
"last": "dean"
}
},
{
"gender": "male",
"name": {
"first": "rubween",
"last": "dean"
}
},
{
"gender": "female",
"name": {
"first": "rubenq",
"last": "dean"
}
}, {
"gender": "female",
"name": {
"first": "rubenr",
"last": "dean"
}
}
];
$.each(obj, function(i, item) {
if(obj[i].gender=="male")
$("#output").append(obj[i].name.first+" - "+obj[i].gender+"<br>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output">
</div>
答案 2 :(得分:0)
您可以使用解决方案
var data = [{
"gender": "male",
"name": {
"first": "rubween",
"last": "dean"
}
},
{
"gender": "male",
"name": {
"first": "rubween",
"last": "dean"
}
},
{
"gender": "female",
"name": {
"first": "rubenq",
"last": "dean"
}
}, {
"gender": "female",
"name": {
"first": "rubenr",
"last": "dean"
}
}
];
$.each(data, function(i){
if(data[i].gender === 'male')
$('body').append(`${data[i].name.first} ${data[i].name.last} <br/>`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
希望这会对你有所帮助。