Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

คู่มือ jQuery find(): การค้นหาองค์ประกอบลูกแบบขั้นตอน

ความแตกต่างระหว่าง JavaScript find() และ jQuery find()

เมธอด find() ของ JavaScript ใช้กับอาร์เรย์เท่านั้น คืนค่าองค์ประกอบแรกที่ผ่านเงื่อนไข ในขณะที่ jQuery find() ใช้กับ Selector และค้นหาเฉพาะองค์ประกอบลูก (Descendants) ภายใน Selector นั้น ทำให้ควบคุมการจัดการ DOM ได้ละเอียดขึ้น

การใช้งาน jQuery find()

ตัวอย่างพื้นฐาน: เปลี่ยนสีข้อความใน <span>

โครงสร้าง HTML:

<div id="main">
  <h2> jQuery find() method example </h2>
  <p> This is an example paragraph. </p>
  <p>We are going to change the color <span>blue</span> to the color blue.</p>
  <div class="green">We are going to change the word <span>green</span> to the color green.</div>
  <p> Every other will word will stay the same. </p>
</div>

โค้ด jQuery:

<script>
  $(document).ready(() => {
    $('p').find('span').css('color', 'blue');
    $('div.green').find('span').css('color', 'green');
  })
</script>

บรรทัดแรก: เลือกทุก <p> แล้วค้นหา <span> ลูก แล้วเปลี่ยนสีเป็นสีน้ำเงิน
บรรทัดที่สอง: เลือก <div class="green"> แล้วค้นหา <span> ลูก แล้วเปลี่ยนสีเป็นสีเขียว

ตัวอย่างขั้นสูง: รายการทำกิจกรรม (To-Do List)

HTML แบบมีรายการซ้อนกัน:

<ul>
  <li class="store">Go to the store 
    <ul>
      <li>Trash bags</li>
      <li>Dish Soap</li>
    </ul>
  </li>
  <li>Take out the trash</li>
  <li>Wash the dishes</li>
</ul>

จีบรายการย่อยภายใต้ "Go to the store":

<script>
  $(document).ready(() => {
    $('li.store').find('li').css('text-decoration', 'line-through')
  })
</script>

ผลลัพธ์: รายการ "Trash bags" และ "Dish Soap" จะถูกขีดทับ

สรุป

jQuery find() ค้นหาและจัดการเฉพาะองค์ประกอบลูกของ Selector ที่ระบุ ทำให้สามารถเปลี่ยนแปลงส่วนใดส่วนหนึ่งของเพจได้อย่างแม่นยำ ความยืดหยุ่นนี้ทำให้ find() มีประโยชน์มากในการพัฒนาเว็บ