jQuery - DOM 元素方法

來源:互聯網
上載者:User

標籤:.text   str   理解   i++   oda   tor   click   body   his   

jQuery DOM 元素方法 - get() 方法執行個體

獲得第一個 p 元素的名稱和值:

<script type="text/javascript">
   $(document).ready(function(){
   $("button").click(function(){
   x=$("p").get(0);
   $("div").text(x.nodeName + ": " + x.innerHTML);
    });
});
</script>

<body>
<p>This is a paragraph</p>
<button>獲得 p DOM 元素</button>
<div></div>
</body>

結果
當點擊時:P: This is a paragraph

文法:$(selector).get(index) 其中selector是所選擇的元素,index是要取出的元素的下標

jQuery DOM 元素方法 - index() 方法


<script type="text/javascript">
   $(document).ready(function(){
   $("li").click(function(){
    alert($(this).index());
    });
});
</script>

<body>
<p>點擊清單項目可獲得其相對於同胞元素的 index 位置:</p>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
</body>

結果如下,點擊元素時會相應的彈出元素的index,例如:點擊coffee時,會彈出 0

點擊清單項目可獲得其相對於同胞元素的 index 位置:


  • Coffee
  • Milk
  • Soda
定義和用法

index() 方法返回指定元素相對於其他指定元素的 index 位置。

這些元素可通過 jQuery 選取器或 DOM 元素來指定。

注釋:如果未找到元素,index() 將返回 -1。

 

第二:


<script type="text/javascript">
  $(document).ready(function(){
  $("button").click(function(){
  alert($(".hot").index($("#favorite")));
  });
});
</script>

<body>
<p>請點擊下面的按鈕,以獲得 id="favorite" 的元素相對於 jQuery 選取器 (class="hot") 的 index:</p>
<button>獲得 index</button>
<ul>
<li>Milk</li>
<li class="hot">Tea</li>
<li class="hot" id="favorite">Coffee</li>
</ul>
</body>

這個結果一點擊時,彈出的下標 是1,如果不寫$("#favorite"),那彈出的是1,寫了則就是相對<li class="hot">Tea</li>裡面的class="hot",結果為1。如果

<li class="hot" id="favorite">Coffee</li>裡面刪除class="hot"那結果肯定是-1,但是刪除<li class="hot">Tea</li>裡面的class="hot"那結果就是0.。

 
jQuery DOM 元素方法 - size() 方法定義和用法

size() 方法返回被 jQuery 選取器匹配的元素的數量。

文法
$(selector).size()
這個就是返回元素數量,很好理解,換一下方法示範一下就行

jQuery DOM 元素方法 - toArray() 方法


<script type="text/javascript">
  $(document).ready(function(){
  $("button").click(function(){
  x=$("li").toArray()
      for (i=0;i<x.length;i++){
           alert(x[i].innerHTML);
       }
     });
});
</script>

<body>
<button>輸出每個清單項目的值</button>
<ul>
<li>Coffee</li>
<li>Milk</li>
<li>Soda</li>
</ul>
</body>

定義和用法

toArray() 方法以數組的形式返回 jQuery 選取器匹配的元素。

文法
$(selector).toArray()
這個也不難,就是以數組的形式返回所匹配的元素

jQuery - DOM 元素方法

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.