我正在显示来自对象数组的数据,但我想过滤结果,以便只显示那些name
属性值为{winner
的对象的1
1}}。
<script>
$(document).ready(function () {
var json = [
{"name":"Name 1","winner":"1"},
{"name":"Name 2","winner":"0"},
{"name":"Name 3","winner":"1"},
{"name":"Name 4","winner":"1"},
{"name":"Name 5","winner":"0"},
];
var li;
for (var i = 0; i < json.length; i++) {
li = $('<li/>');
li.append(json[i].name);
$('#feed').append(li);
}
});
</script>
HTML应如下所示(仅在获胜者为真时显示结果,winner
= 1
)
<ul id="feed" >
<li>Name 1</li>
<li>Name 3</li>
<li>Name 4</li>
</ul>
答案 0 :(得分:4)
您可以尝试使用if
声明:
for (var i = 0; i < json.length; i++) {
if (json[i].winner === '1') {
li = $('<li/>');
li.append("<font size='+1'>" + json[i].name + "</font>");
$('#feed').append(li);
}
}
答案 1 :(得分:3)
只需在循环中添加条件
for (var i = 0; i < json.length; i++) {
if (json[i].winner === "1") {
$('<li />', {text : json[i].name}).appendTo('#feed');
}
}
答案 2 :(得分:3)
您必须添加一个if语句来检查获胜者是否等于1:
var json = [
{"name":"Name 1","winner":"1"},
{"name":"Name 2","winner":"0"},
{"name":"Name 3","winner":"1"},
{"name":"Name 4","winner":"1"},
{"name":"Name 5","winner":"0"},
];
var li;
for (var i = 0; i < json.length; i++) {
if(json[i].winner == "1"){ //add this
li = $('<li/>');
li.append("<font size='+1'>" + json[i].name + "</font>");
$('#feed').append(li);
}
}
答案 3 :(得分:3)
试试这个:
var ul = $('ul#feed');
for (var i = 0; i < json.length; i++) {
if (json[i].winner == 1) {
ul.append("<li>" + json[i].name + "</li>");
}
}