andSelf() trong jQuery



Miêu tả

Phương thức andSelf() trong jQuery thêm sự chọn lọc trước tới sự chọn lọc hiện tại.

Cú pháp

Sau đây là cú pháp để sử dụng andSelf() trong jQuery:

selector.andSelf( )

Tham số

Chi tiết tham số được sử dụng trong phương thức andSelf() trong jQuery:

  • NA.

Quảng cáo

Ví dụ

Ví dụ đơn giản sau minh họa cách sử dụng của andSelf() trong jQuery.

<html>
   <head>
      <title>The jQuery Example</title>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
		
      <script>
         $(document).ready(function(){
            $("div").find("p").andSelf().addClass("border");
         });
      </script>
		
      <style>
         p, div { margin:5px; padding:5px; }
         .border { border: 2px solid red; }
         .background { background:yellow; }
      </style>
		
   </head>
	
   <body>
	
      <div>
         <p>First Paragraph</p>
         <p>Second Paragraph</p>
      </div>
		
   </body>
</html>

Ở đây, border sẽ được thêm vào sự lựa chọn trước mà là một khối và sau đó là sự chọn lựa thứ hai mà là đoạn văn, như dưới đây:

Nếu bạn gỡ bỏ phương thức andSelf() thì border sẽ chỉ áp dụng cho đoạn văn.

<html>
   <head>
      <title>The jQuery Example</title>
      <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
		
      <script>
         $(document).ready(function(){
            $("div").find("p").andSelf().addClass("border");
         });
      </script>
		
      <style>
         p, div { margin:5px; padding:5px; }
         .border { border: 2px solid red; }
         .background { background:yellow; }
      </style>
		
   </head>
	
   <body>
	
      <div class="border">
         <p class="border">First Paragraph</p>
         <p class="border">Second Paragraph</p>
      </div>
		
   </body>
</html>
Quảng cáo

Nó sẽ cho kết quả:

Các bài học jQuery khác tại VietJack:


truy_cap_dom_trong_jquery.jsp