开发者

Project new objects from jQuery selector

Is there a way to project objects from a jQuery selection? As a simplified example, let's say I want an array of objects, corresponding to my page's anchors; in each object, txt开发者_C百科 refers to the anchor's text, and val refers to the data-id attr therein.

var result = [];
$("a").each(function(i, o) {     
    result.push({ txt: $(o).text(), val: $(o).data("id") }); 
});
doSomething(result);

Is it possible to do something like a C# Select:

doSomething($("a").select(
    function(i, o) { return { txt: $(o).text(), val: $(o).data("id") }; 
});


You could use the .map() method to project a set:

doSomething($("a").map(function(o, i) { 
    return { txt: $(o).text(), val: $(o).data("id") }; 
});

Remark: notice that the index and element parameters are inversed in the anonymous callback compared to the .each method. Don't ask why :-) If you don't care about the index you could simply omit them and do this:

doSomething($("a").map(function() { 
    return { txt: $(this).text(), val: $(this).data("id") }; 
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜