码迷,mamicode.com
首页 > Web开发 > 详细

jQuery 遍历

时间:2016-08-19 13:05:07      阅读:227      评论:0      收藏:0      [点我收藏+]

标签:

本代码来源:http://www.imooc.com/code/4703 叶子钗mooc

遍历父节点:

function parent(elem) {
  var parent = elem.parentNode;
  // 如果存在父节点,且父节点不是文档碎片的话,返回父节点
  return parent && parent.nodeType !== 11 ? parent : null;
}


function parents(elem){
  var matched = [];
  // 未匹配到根目录document前,迭代如果elem 有父节点,则push进match
  while ( (elem = elem[ parentNode ]) && elem.nodeType !== 9 ) {
    if ( elem.nodeType === 1 ) {
      matched.push( elem );
    }
  }
  return matched;
}

function parentsUntil(elem, filter) {
  var matched = [],
      until,
      truncate = filter !== undefined;
  while ((elem = elem[parentNode]) && elem.nodeType !== 9) {
    if (elem.nodeType === 1) {
      if (truncate) {
        // 与parents类似,仅仅增加匹配到filter跳出匹配
        if(elem.nodeName.toLowerCase() == filter){
          break;
        }
      }
      matched.push(elem);
    }
  }
  return matched;
}

 

遍历同胞节点:

function dir(elem, dir, until) {
  var matched = [],
      truncate = until !== undefined;
  while ((elem = elem[dir]) && elem.nodeType !== 9) {
    if (elem.nodeType === 1) { // nextSibling previousSibling会将空格匹配,且返回结果是undefined
      if (truncate) {
        if (elem.nodeName.toLowerCase() == until || elem.className == until) {
          break;
        }
      }
      matched.push(elem);
    }
  }
  return matched;
}


function nextAll(elem) {
  // 遍历全部下一个同胞节点
  return dir(elem, "nextSibling");
}

function prevAll(elem) {
  // 遍历全部上一个同胞节点
  return dir(elem, "previousSibling");
}

function nextUntil(elem, until) {
  // 遍历全部下个同胞节点,直到until
  return dir(elem, "nextSibling", until);
}

function prevUntil(elem, until) {
  // 遍历全部上一个同胞节点,直到until
  return dir(elem, "previousSibling", until);
}

 

 

function sibling(cur, dir) {
 // 遍历同胞 
  while ((cur = cur[dir]) && cur.nodeType !== 1) {}
  return cur;
}

function next(elem) {
 // 遍历下一个兄弟
  return sibling(elem, "nextSibling");
}

function prev(elem) {
 // 遍历上一个兄弟
  return sibling(elem, "previousSibling");
}

 

遍历后代

  function sibling(n, elem) {
    // sibling 在jQuery 中的写法
    var matched = [];
    for (; n; n = n.nextSibling) { //如果存在下一个兄弟节点
      if (n.nodeType === 1 && n !== elem) { //是元素节点,且不是当前选择器元素
        matched.push(n);
      }
    }
    return matched;
  }

 function children( elem ) {
        return sibling( elem.firstChild );
    }

find() 使用的是sizzle 引擎

不过在支持querySelectAll() 的浏览器中可以

function find(elem, selector) {
  return elem.querySelectorAll(selector);
}

 

jQuery 遍历

标签:

原文地址:http://www.cnblogs.com/dongcheck/p/5786873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!