jQuery 没有比你的选项 B 更好的东西了。我长期以来一直认为这是一个缺失的功能,因为我也经常想要类似的东西。幸运的是,创建自己的方法并不难:
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));
}
同样可以对nextFind()
also.
在您的示例中,而不是这样:
$(this).prevAll("parent" + parentId).eq(0);
你会用这个:
$(this).prevFind("parent" + parentId)
而且,这是两者的实现prevFind()
and nextFind()
使用一些通用代码:
(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));
这是小提琴:http://jsfiddle.net/nDYDL/1/