admin管理员组文章数量:1403364
Can someone tell me how to update the following code to just get the first item that's returned in an object (data)? I know using each() for just one item isn't very efficient and would like to improve it.
$(data).each(function(num, entry){
if ( num > 1 ) return false;
});
Here's an example of what data
is:
[
{
"id": 1,
"title": "My post",
"permalink":"http:\/\/site\/page.html\/",
"date":" 2011-05-10
}
]
Can someone tell me how to update the following code to just get the first item that's returned in an object (data)? I know using each() for just one item isn't very efficient and would like to improve it.
$(data).each(function(num, entry){
if ( num > 1 ) return false;
});
Here's an example of what data
is:
[
{
"id": 1,
"title": "My post",
"permalink":"http:\/\/site.\/page.html\/",
"date":" 2011-05-10
}
]
Share
Improve this question
edited May 10, 2011 at 20:32
Cofey
asked May 10, 2011 at 20:13
CofeyCofey
11.4k16 gold badges54 silver badges75 bronze badges
2 Answers
Reset to default 9Update 2:
As data
is just an array (I assume the JSON is already parsed (if not you can use jQuery.parseJSON
or JSON.parse
)), you can get the first element with simple array access:
var first = data[0];
Read more about arrays.
Old answer:
Try
$(data).first() // returns jQuery object
// or
$(data).eq(0) // returns jQuery object
// or
$(data).get(0) // returns DOM object
// or
$(data)[0] // returns DOM object
depending on the data you have and what you want to do.
Update:
If data
is actually a JavaScript object, then there is no need to pass it to jQuery (jQuery is mostly for working with the DOM).
Just loop over it with
for(var prop in data) {
}
But you cannot get the "first" property because they are unordered.
If it is an array, just use data[0]
.
To help you more, you should post what data
is.
You can do this:
$(data).get(0); //same as $(data)[0]
本文标签: jQueryJavaScript equivalent of each() for a single elementStack Overflow
版权声明:本文标题:jQueryJavaScript equivalent of each() for a single element? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744409278a2604868.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论