HTMLDialogElement: returnValue 屬性

Baseline 已廣泛支援

此特性已經十分成熟,可在許多裝置和瀏覽器版本上使用。自 2022 年 3 月起,它已在各瀏覽器中可用。

HTMLDialogElement 介面的 returnValue 屬性是一個字串,表示 <dialog> 元素關閉時的返回值。您可以直接設定該值(dialog.returnValue = "result"),或者透過向 close()requestClose() 提供字串引數來設定。

一個表示對話方塊 returnValue 的字串。預設為一個空字串("")。

示例

檢查返回值

以下示例顯示了一個開啟對話方塊的按鈕。對話方塊會詢問使用者是否要接受服務條款提示。

對話方塊包含“接受”或“拒絕”按鈕:當用戶單擊其中一個按鈕時,按鈕的點選處理程式會關閉對話方塊,並將使用者的選擇傳遞給 close() 函式。這會將選擇賦值給對話方塊的 returnValue 屬性。

在對話方塊的 close 事件處理程式中,示例更新主頁的狀態文字以記錄 returnValue

如果使用者在未單擊按鈕的情況下關閉了對話方塊(例如,按 Esc 鍵),則不會設定返回值。

HTML

html
<dialog id="termsDialog">
  <p>Do you agree to the Terms of Service (link)?</p>
  <button id="declineButton" value="declined">Decline</button>
  <button id="acceptButton" value="accepted">Accept</button>
</dialog>
<p>
  <button id="openDialogButton">Review ToS</button>
</p>
<p id="statusText"></p>

JavaScript

js
const dialog = document.getElementById("termsDialog");
const statusText = document.getElementById("statusText");

const openDialogButton = document.getElementById("openDialogButton");
const declineButton = document.getElementById("declineButton");
const acceptButton = document.getElementById("acceptButton");

openDialogButton.addEventListener("click", () => {
  dialog.showModal();
});

declineButton.addEventListener("click", closeDialog);
acceptButton.addEventListener("click", closeDialog);

function closeDialog(event) {
  const button = event.target;
  dialog.close(button.value);
}

dialog.addEventListener("close", () => {
  statusText.innerText = dialog.returnValue
    ? `Return value: ${dialog.returnValue}`
    : "There was no return value";
});

結果

嘗試單擊“檢視服務條款”,然後在對話方塊中選擇“接受”或“拒絕”按鈕,或者按 Esc 鍵關閉對話方塊,並觀察不同的狀態更新。

規範

規範
HTML
# dom-dialog-returnvalue-dev

瀏覽器相容性

另見

  • 實現此介面的 HTML 元素:<dialog>