Create a jQuery object collection from separate jQuery objects
$.fn.sortByDepth = function() {
var ar = [];
var result = $([]);
$(this).each(function() {
ar.push({length: $(this).parents().length, elmt: $(this开发者_如何学Go)});
});
ar.sort(function(a,b) {
return b.length - a.length;
});
for (var i=0; i<ar.length; i++) {
result.add(ar[i].elmt);
};
alert(result.length);
return result;
};
In this function I try to create a jQuery collection from separate jQuery object. How can i do that ?
The code below doesn't work:
result.add(ar[i].elmt);
The jsfiddle: http://jsfiddle.net/hze3M/14/
.add()
returns a new jQuery object. Change this line:
result.add(ar[i].elmt);
to this:
result = result.add(ar[i].elmt);
This still won't work, though
As of jQuery 1.4 the results from .add() will always be returned in document order (rather than a simple concatenation).
So you just use a vanilla JS array, push()
the sorted elements into it, and then $()
the whole thing.
Other code cleanup:
$.fn.sortByDepth = function() {
var ar = this.map(function() {
return {length: $(this).parents().length, elt: this}
}).get(),
result = [],
i = ar.length;
ar.sort(function(a, b) {
return a.length - b.length;
});
while (i--) {
result.push(ar[i].elt);
}
return $(result);
};
var x = $('input').sortByDepth().map(function() {
return this.id;
}).get().join(' - ');
$('#selection').text(x);
http://jsfiddle.net/mattball/AqUQH/.
.add
returns a new object, and does not modify the old one.
Try changing:
result.add(ar[i].elmt);
To:
result = result.add(ar[i].elmt);
Also, $([])
is unneeded, you can just do var result = $();
精彩评论