หมวดหมู่: Web

การใช้ jQuery selectors APIการใช้ jQuery selectors API

การเขียน JavaScript มักเริ่มต้นโดยการเลือกออบเจ็คที่จะทำงานด้วย ระบุคำสั่งหรือระบุเหตุการณ์ให้ทำงานต่าง ๆ การเลือกออบเจ็คในภาษา JavaScript ถ้ามีเงือนไขที่ซับซ้อนก็จะเขียนได้ยากเพราะต้องใช้วิธีไต่ DOM เข้าไปที่ละชั้น ๆ JQuery เข้ามาแก้ปัญหาส่วนนี้โดยมี API selectors เข้ามาทดแทนให้เขียนได้ง่ายขึ้น อย่าง เช่น

<form id="demoF"> <table class="democlass"> <tr> <td><label for="q0">เพศ</label> <select name="prename" id="q0"> <option value="1">นาย</option> <option value="2">นาง</option> <option value="3">นางสาว</option> </select></td> </tr> <tr> <td><label for="q1">ชื่อ</label> <input name="firstname" id="q1" /></td> </tr> <tr> <td><label for="q2">นามสกุล</label> <input name="lastname" id="q1" /></td> </tr> <tr> <td><label for="q3">ตกลง</label> <input type="checkbox" name="agree" id="q3" value="agree" /></td> </tr> </table>
</form>
เลือกรูปแบบ JQueryตัวอย่าง
id$ (‘#ชื่อ id’) $ (‘#demoF’)
attribute$ (‘[attribute|=value]’) $ (‘[name|=firstname]’)
Checkbox ที่ถูกเลือก$ (“:checkbox”) $ (‘:checkbox’)
Selected ที่ถูกเลือก$ (“select option:selected”) $ (“select option:selected”)
เลือกจาก CSS class$ (.ชื่อ class) $ (‘.democlass’)
ลูกตัวแรก$ (“แม่:first”) $ (“tr:first”)