首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >jQuery .cousins()方法

jQuery .cousins()方法
EN

Stack Overflow用户
提问于 2013-09-21 03:08:59
回答 1查看 1.4K关注 0票数 1

我最终希望.cousins(selector=null, uplimiter=-1, upstart=1,excludeself=true),但我不知道这是否有可能为一个插件。如果是,那么我希望将这些作为参数对象传递。

更新--这是工作代码,但excludeself部件除外,它的目的是丢弃上下文的任何子结果。

代码语言:javascript
复制
(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的一个示例:

代码语言:javascript
复制
.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'),并让它返回第一次出现的火柴,因为它爬上树。

EN

回答 1

Stack Overflow用户

发布于 2013-09-21 07:21:42

好吧,可以找到表兄弟姐妹:

代码语言:javascript
复制
void function($) {
    $.fn.cousins = function(selector) {
        return this.parent().siblings().children(selector);
        //         ^ parent ^ uncles   ^ cousins
    };
}(jQuery);

修剪中间结果是相当容易的。

默认情况下,节点本身被排除在外,但是您只需使用.andSelf()就可以得到它。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18928485

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档