我最终希望.cousins(selector=null, uplimiter=-1, upstart=1,excludeself=true),但我不知道这是否有可能为一个插件。如果是,那么我希望将这些作为参数对象传递。
更新--这是工作代码,但excludeself部件除外,它的目的是丢弃上下文的任何子结果。
(function($) {
$.fn.cousins = function(selector,uplimit,upstart,excludeself) {
upstart=upstart||1;
uplimit=uplimit||-1;
excludeself=arguments.length<4?true:excludeself;
if (typeof selector==='object') {
upstart=(typeof selector.upstart!=='undefined')?selector.upstart:upstart;
uplimit=(typeof selector.uplimit!=='undefined')?selector.uplimit:uplimit;
excludeself=(typeof selector.excludeself!=='undefined')?selector.excludeself:excludeself;
selector=selector.selector;
}
var cousins=null;
var upat=0;
var at=this;
var that=this;
if (at.length===0) {
console.log('r 1');
return at;
}
var upstart_ct=upstart;
while(at.length>0&&upstart_ct>0) {
at=at.parent();upat++;
console.log(at.attr('id'));
upstart_ct--;
if (at.length===0) {
return at;
}
}
console.log('checkiing...');
while ((cousins===null||cousins.length===0)&&(upat<uplimit||uplimit==-1)) {
at.each(function() {
if (cousins!==null) {
return false;
}
var items = $(this).find(selector);
console.log('found:'+items.length);
if (0) {// need to excludeself here
items=items.filter(function(idx){
var me=$(this);
var ps=me.parents();
if (ps.indexOf(that)) {//?? not going to work huh HALP
}
});
}
if (items.length!=0) {
if (cousins===null) {
console.log('assigning to cousins...');
cousins=items;
return false;
}
}
});
if (cousins!==null) {
console.log('cousins.length'+cousins.length);
}
if (cousins) {
break;
}
at=at.parent();upat++;
console.log('going up...'+upat);
console.log(at.attr('id'));
if (at.length===0) {
cousins=at;
break;
}
}
return cousins;
}
})(jQuery);我以前从未写过jQuery插件,所以我需要帮助。
下面是html的一个示例:
.item
.item-hdr
.item-hdr-btn <<source
.item-body-text-area <<an example of excludeself, do not return this in set
.item-body
.item-body-textarea <<target因此,我想说$('.item-hdr-btn').cousins('.item-body-textarea'),并让它返回第一次出现的火柴,因为它爬上树。
发布于 2013-09-21 07:21:42
好吧,可以找到表兄弟姐妹:
void function($) {
$.fn.cousins = function(selector) {
return this.parent().siblings().children(selector);
// ^ parent ^ uncles ^ cousins
};
}(jQuery);修剪中间结果是相当容易的。
默认情况下,节点本身被排除在外,但是您只需使用.andSelf()就可以得到它。
https://stackoverflow.com/questions/18928485
复制相似问题