jQuery prop()วิธี การ

❮ วิธีการ jQuery HTML/CSS

ตัวอย่าง

เพิ่มและลบคุณสมบัติชื่อ "สี":

$("button").click(function(){
  var $x = $("div");
  $x.prop("color", "FF0000");
  $x.append("The color property: " + $x.prop("color"));
  $x.removeProp("color");
});

ความหมายและการใช้งาน

prop() วิธีตั้งค่าหรือส่งคืนคุณสมบัติและค่าขององค์ประกอบที่เลือก

เมื่อวิธีนี้ใช้เพื่อคืนค่าคุณสมบัติ จะคืนค่าขององค์ประกอบที่ตรงกัน FIRST

เมื่อใช้วิธีนี้เพื่อตั้งค่าคุณสมบัติ จะตั้งค่าคู่คุณสมบัติ/ค่าอย่างน้อยหนึ่งคู่สำหรับชุดขององค์ประกอบที่ตรงกัน

หมายเหตุ:ควรใช้เมธอด prop() เพื่อดึงค่าคุณสมบัติ เช่น คุณสมบัติ DOM (เช่น tagName, nodeName, defaultChecked) หรือคุณสมบัติที่คุณกำหนดเอง

เคล็ดลับ:ในการดึงแอตทริบิวต์ HTML ให้ใช้attr()วิธีการแทน

เคล็ดลับ:หากต้องการลบคุณสมบัติให้ใช้เมธอดremoveProp()


ไวยากรณ์

ส่งกลับค่าของคุณสมบัติ:

$(selector).prop(property)

ตั้งค่าคุณสมบัติและค่า:

$(selector).prop(property,value)

ตั้งค่าคุณสมบัติและค่าโดยใช้ฟังก์ชัน:

$(selector).prop(property,function(index,currentvalue))

ตั้งค่าคุณสมบัติและค่าหลายรายการ:

$(selector).prop({property:value, property:value,...})

Parameter Description
property Specifies the name of the property
value Specifies the value of the property
function(index,currentvalue) Specifies a function that returns the property value to set
  • index - Receives the index position of the element in the set
  • currentvalue - Receives the current property value of selected elements

ลองด้วยตัวคุณเอง - ตัวอย่าง


prop() และ attr() อาจคืนค่าที่แตกต่างกัน ตัวอย่างนี้แสดงความแตกต่างเมื่อใช้เพื่อส่งคืนสถานะ "ตรวจสอบแล้ว" ของช่องทำเครื่องหมาย


❮ วิธีการ jQuery HTML/CSS