我最终会喜欢.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')
让它在爬上树时返回第一次出现的匹配项。