作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
好吧,我是一个 JSON 菜鸟,只有基本的 jQuery 知识,而且我到处寻找解决方案,但找不到。非常感谢任何帮助。
我需要:
1) 遍历 JSON 数组(有效)
2) 显示“mbrname”的前两个结果
3) 然后显示其余结果的计数。
我正在成功循环并显示所有 mbrname 结果。但不知何故我只需要显示前两个,如果有更多显示“+ # others”
这是最终产品的屏幕截图:
这是我的代码现在产生的结果:
这是我的 JSON:
{
"messages":{
"message":[
{
"date-time":"June 2, 2013 12:22 pm",
"subject":"This is the message subject",
"msg-string":"001",
"newmsg":"true",
"attach":"shop-cart",
"recipient":[
{
"mbrname":"D. Craig",
"mbr-href":"#craig"
},
{
"mbrname":"N. McCoy",
"mbr-href":"#mccoy"
},
{
"mbrname":"J. Smith",
"mbr-href":"#smith"
},
{
"mbrname":"B. Wardlaw",
"mbr-href":"#wardlaw"
}
]
},
{
"date-time":"May 23, 2013 12:22 pm",
"subject":"This is a great subject",
"attach":"none",
"msg-string":"002",
"newmsg":"true",
"recipient":[
{
"mbrname":"D. Craig",
"mbr-href":"#craig"
},
{
"mbrname":"N. McCoy",
"mbr-href":"#mccoy"
}
]
},
{
"date-time":"May 11, 2013 12:22 pm",
"subject":"Interested in your tomatoes",
"attach":"shop-cart",
"msg-string":"003",
"newmsg":"false",
"recipient":[
{
"mbrname":"J. Smith",
"mbr-href":"#smith"
}
]
}
]
}
}
这是我的“mbrname”部分的 jquery,它成功地提取了名称并将它们附加到我的 HTML 中:
$.each (message.recipient, function (message, recipient) {
var mbrPart = recipient.mbrname + ', ';
var currentUser = $('#' + newID + ' .name');
$(currentUser).append(mbrPart);
});
在此先感谢您的帮助!
最佳答案
我会保持简单,不需要做任何循环:
var recipientString = message.recipient[0].mbrname;
var count = message.recipient.length;
if (count > 1)
recipientString += ', ' + message.recipient[1].mbrname;
if (count > 2)
recipientString += ' + ' + (count - 2) + ' others';
$('#' + newID + ' .name').append(recipientString);
关于javascript - 遍历 JSON 数组,显示两个然后计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23018832/
我是一名优秀的程序员,十分优秀!