jQuery的遍歷結構設計——同胞元素的遍歷例子

一、遍歷的接口分爲 祖先 同胞兄弟 後代 過濾javascript

基礎知識: nodeType 元素類型 節點類型 元素 1 屬性 2 文本 3 註釋 8 文檔 9html

nodeName 元素節點的nodeName是標籤名稱 屬性節點的nodeName是屬性名稱 文本節點的nodeName永遠是 #text 文檔節點的nodeName永遠是 #documentjava

二、同胞遍歷的例子:node

<!-- lang: html -->
<!DOCTYPE HTML>
<!-- lang: html -->
<html>
<!-- lang: html -->
<head>
<!-- lang: html -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<!-- lang: html -->
<script src="http://img.mukewang.com/down/540812440001e40e00000000.js" type="text/javascript"></script>
<!-- lang: html -->
<!-- <script type="text/javascript" src="../jquery-2.1.1.js"></script> -->
<!-- lang: html -->
<title></title>
<!-- lang: html -->
</head>
<!-- lang: html -->
<body>
<!-- lang: html -->

<!-- lang: html -->
<button id="test1">jQuery遍歷同胞</button>
<!-- lang: html -->
<button id="test2">模擬遍歷同胞</button>
<!-- lang: html -->

<!-- lang: html -->
<ul class="level-1">
<!-- lang: html -->
  <li class="item-i">I</li>
<!-- lang: html -->
  <li class="item-ii">II
<!-- lang: html -->
    <ul class="level-2">
<!-- lang: html -->
      <li class="item-a">A</li>
<!-- lang: html -->
      <li class="item-b">B
<!-- lang: html -->
        <ul class="level-3">
<!-- lang: html -->
          <li class="item-1">1</li>
<!-- lang: html -->
          <li class="item-2">2</li>
<!-- lang: html -->
          <li class="item-3">3</li>
<!-- lang: html -->
        </ul>
<!-- lang: html -->
      </li>
<!-- lang: html -->
      <li class="item-c">C</li>
<!-- lang: html -->
    </ul>
<!-- lang: html -->
  </li>
<!-- lang: html -->
  <li class="item-iii">III</li>
<!-- lang: html -->
</ul>
<!-- lang: html -->

<!-- lang: html -->

js代碼jquery

function dir(elem, dir, until) { var matched = [], truncate = until !== undefined; while ((elem = elem[dir]) && elem.nodeType !== 9) { if (elem.nodeType === 1) { if (truncate) { if (elem.nodeName.toLowerCase() == until || elem.className == until) { break; } } matched.push(elem); } } return matched; }ui

function nextAll(elem) { return dir(elem, "nextSibling"); }code

function prevAll(elem) { return dir(elem, "previousSibling"); }htm

function nextUntil(elem, until) { return dir(elem, "nextSibling", until); }接口

function prevUntil(elem, until) { return dir(elem, "previousSibling", until); }ip

$("#test1").click(function(){ var item = $('li.item-ii'); alert(item.nextAll()[0].className) alert(item.prevAll()[0].className) alert(item.nextUntil('.end')[0].className) alert(item.prevUntil('.first')[0].className) })

$("#test2").click(function(){ var item = document.querySelectorAll('li.item-ii')[0] alert(nextAll(item)[0].className) alert(prevAll(item)[0].className) alert(nextUntil(item, '.end')[0].className) alert(prevUntil(item, '.first')[0].className) })

相關文章
相關標籤/搜索