HTMLDialogElement: returnValue 属性
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>。