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

ปิดใช้งานปุ่มด้วย jQuery: ใช้ prop() Method

หลายเหตุผลต้อง disable ปุ่มใน web app: ป้องกันเพิ่มสินค้าหมดสต็อคในตะกร้า หรือไม่ให้คลิกปุ่มซ้ำหลัง actionPerformed jQuery ไม่มี method disable ปุ่มโดยตรง

ใช้ prop() method (เพิ่มใน jQuery 1.6) แทน มาแก้ปัญหาการดึง property values ของ selected elements ก่อนหน้านี้ใช้ attr() ดึง attribute values แต่ property และ attribute ผสมกันให้ผล unpredictable jQuery 1.6 introduce prop() แยกความรับผิดชัดเจน "disabled" เป็น property ของ HTML button element จึงใช้ prop()

prop() jQuery Syntax

prop() เรียกบน selected element (button ในที่นี้) disable ปุ่ม id="btn":

<button id='btn' type='submit'> Button is Disabled </button>

ตั้งค่า property "disabled" = true:

$('#btn').prop('disabled', true)

prop() รับ property name เป็น string argument แรก boolean value argument ที่ 2 (true/false) ปุ่มจะกลายเป็น unclickable

ตัวอย่างจริง: E-commerce Disable "Add to Cart"

Shopping app disable "Add to Cart" ถ้าสินค้าหมดสต็อค (soldOut: true)

<button class='add' type='submit'> Add to Cart </button>
<div></div>

สร้าง product object และ callback function:

const product = {
  name: 'Jacket',
  price: 50.00,
  soldOut: false
};

$(document).ready(function() {
  $('button.add').click(function(event) {
    event.preventDefault();
    alert(JSON.stringify(product.soldOut));
    if (product.soldOut) {
      $('.add').prop('disabled', true);
    } else {
      $('div').append(product.name);
    }
  });
});

product.soldOut = false -> แสดง Jacket ใน div

product.soldOut = true -> ปุ่ม Add to Cart disabled ไม่ให้เพิ่มสินค้าหมดสต็อค

สรุป

jQuery ไม่มี method disable ปุ่มโดยตรง ใช้ prop() ตั้ง property "disabled" = true แทน ตัวอย่าง e-commerce แสดงประโยชน์จริง: guide user experience ป้องกันเพิ่มสินค้าหมดสต็อค สำคัญใน web development