IDBKeyRange: phương thức tĩnh only()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

Note: This feature is available in Web Workers.

Phương thức tĩnh only() của giao diện IDBKeyRange tạo một phạm vi khóa mới chỉ chứa một giá trị duy nhất.

Cú pháp

js
IDBKeyRange.only(value)

Tham số

value

Giá trị cho phạm vi khóa mới.

Giá trị trả về

IDBKeyRange: Phạm vi khóa vừa được tạo.

Ngoại lệ

DataError DOMException

Được ném ra nếu tham số value không phải là một khóa hợp lệ.

Ví dụ

Ví dụ sau minh họa cách dùng phạm vi khóa chỉ chứa một giá trị. Ở đây chúng ta khai báo keyRangeValue = IDBKeyRange.only("A"); - một phạm vi chỉ bao gồm giá trị "A". Chúng ta mở một transaction (dùng IDBTransaction) và một object store, rồi mở một cursor bằng IDBObjectStore.openCursor, với keyRangeValue là giá trị phạm vi khóa tùy chọn. Điều này có nghĩa là cursor chỉ truy xuất bản ghi có giá trị khóa "A".

Note: Để có ví dụ đầy đủ hơn cho phép bạn thử nghiệm phạm vi khóa, hãy xem repo IDBKeyRange của chúng tôi (xem ví dụ trực tiếp nữa.

js
function displayData() {
  const keyRangeValue = IDBKeyRange.only("A");

  const transaction = db.transaction(["fThings"], "readonly");
  const objectStore = transaction.objectStore("fThings");

  objectStore.openCursor(keyRangeValue).onsuccess = (event) => {
    const cursor = event.target.result;
    if (cursor) {
      const listItem = document.createElement("li");
      listItem.textContent = `${cursor.value.fThing}, ${cursor.value.fRating}`;
      list.appendChild(listItem);

      cursor.continue();
    } else {
      console.log("Entries all displayed.");
    }
  };
}

Thông số kỹ thuật

Specification
Indexed Database API 3.0
# ref-for-dom-idbkeyrange-only①

Tương thích trình duyệt

Xem thêm