I have table rows like so:
...
-
jQuery does not have something better than your option B. I've long thought this was a missing piece of functionality as I've regularly wanted something like it too. Fortunately, it's not too hard to make your own method:
jQuery.fn.prevFind = function(selector) {
var elems = [];
this.each(function(i, item) {
while (item = item.previousSibling) {
if (item.nodeType == 1) {
if ($(item).is(selector)) {
elems.push(item);
break;
}
}
}
});
return(this.pushStack(elems, "prevFind", selector));
}
The same could be done for a nextFind()
also.
In your example, instead of this:
$(this).prevAll("parent" + parentId).eq(0);
you would use this:
$(this).prevFind("parent" + parentId)
And, here's an implementation of both prevFind()
and nextFind()
that uses some common code:
(function($) {
$.each({
'prevFind' : 'previousSibling',
'nextFind' : 'nextSibling'
}, function(method, dir) {
$.fn[method] = function (selector) {
var elems = [];
this.each(function(i, item) {
while (item = item[dir]) {
if (item.nodeType == 1) {
if ( $.find.matches(selector, [item]).length ) {
elems.push(item);
break;
}
}
}
});
return this.pushStack(elems, method, selector);
};
});
}(jQuery));
Here's the fiddle: http://jsfiddle.net/nDYDL/1/
讨论(0)
- 热议问题