ZetCode

JavaScript window.confirm

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 window.confirm 方法。此方法显示一个模态对话框,其中包含一条消息和两个按钮:确定和取消。它通常用于在继续操作之前获取用户确认。

基本定义

window.confirm 方法显示一个对话框,其中包含指定的文本消息以及“确定”/“取消”按钮。如果用户单击“确定”,它将返回 true,如果用户单击“取消”或关闭对话框,它将返回 false

此方法是浏览器窗口对象的一部分,在所有现代浏览器中都可用。对话框的外观由浏览器决定,无法使用 CSS 或 JavaScript 进行自定义。

基本确认对话框

本示例演示了 window.confirm 的最简单用法,用于在继续操作之前获取用户确认。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic Confirm</title>
</head>
<body>

<button onclick="confirmAction()">Delete Item</button>

<script>
    function confirmAction() {
        const confirmed = window.confirm('Are you sure you want to delete this item?');
        if (confirmed) {
            console.log('Item deleted');
        } else {
            console.log('Deletion canceled');
        }
    }
</script>

</body>
</html>

在此基本示例中,单击按钮会触发一个确认对话框。用户的选择决定了哪个消息会被记录到控制台。

这演示了 window.confirm 的基本用法,用于在执行删除等潜在的破坏性操作之前获取用户确认。

导航前确认

本示例展示了如何使用 window.confirm 防止在有未保存更改的情况下意外导航离开页面。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Confirm Navigation</title>
</head>
<body>

<a href="https://example.com" id="externalLink">Visit External Site</a>

<script>
    document.getElementById('externalLink').addEventListener('click', function(e) {
        const confirmed = window.confirm('You are about to leave this site. Continue?');
        if (!confirmed) {
            e.preventDefault();
        }
    });
</script>

</body>
</html>

在这里,我们向一个链接添加了一个点击事件监听器,该链接会显示一个确认对话框。如果用户取消,我们将阻止默认的导航行为。

这种模式对于在用户导航离开包含重要未保存数据的页面或访问外部站点之前向用户发出警告非常有用。

确认表单提交

本示例演示了如何使用 window.confirm 来验证表单提交。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Confirm Form</title>
</head>
<body>

<form id="myForm">
    <input type="text" name="username" placeholder="Username" required>
    <button type="submit">Submit</button>
</form>

<script>
    document.getElementById('myForm').addEventListener('submit', function(e) {
        const confirmed = window.confirm('Are you sure you want to submit this form?');
        if (!confirmed) {
            e.preventDefault();
        }
    });
</script>

</body>
</html>

在此示例中,我们拦截了表单提交事件并显示了一个确认对话框。只有当用户确认后,表单才会提交。

这种技术对于重要表单特别有用,因为意外提交可能会产生重大后果,例如购买或注册。

带有自定义操作的确认

本示例展示了如何根据用户的确认选择执行不同的操作。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Custom Actions</title>
</head>
<body>

<button onclick="handleSubscription()">Manage Subscription</button>
<p id="status">Status: Active</p>

<script>
    function handleSubscription() {
        const confirmed = window.confirm('Do you want to cancel your subscription?');
        const statusElement = document.getElementById('status');
        
        if (confirmed) {
            statusElement.textContent = 'Status: Canceled';
            console.log('Subscription canceled');
        } else {
            statusElement.textContent = 'Status: Active (kept)';
            console.log('Subscription maintained');
        }
    }
</script>

</body>
</html>

在这里,我们使用确认结果根据用户的选择以不同的方式更新 UI。状态消息会更改以反映订阅状态。

这展示了 window.confirm 如何集成到更复杂的工作流程中,其中可能基于用户输入产生不同的结果。

链式确认

本示例展示了如何为多步流程使用多个确认对话框。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Chaining Confirms</title>
</head>
<body>

<button onclick="resetSystem()">Reset System</button>

<script>
    function resetSystem() {
        const confirm1 = window.confirm('This will reset all settings. Continue?');
        if (!confirm1) return;
        
        const confirm2 = window.confirm('WARNING: This cannot be undone. Proceed?');
        if (!confirm2) return;
        
        const confirm3 = window.confirm('Final confirmation. Reset now?');
        if (confirm3) {
            console.log('System reset initiated');
        } else {
            console.log('Reset canceled');
        }
    }
</script>

</body>
</html>

在此示例中,我们链式调用了多个确认对话框,以确保用户确实想要执行关键系统重置。每个步骤都必须得到确认。

这种模式对于危险操作很有用,您希望添加多个确认层来防止意外执行。

来源

MDN window.confirm 文档

在本文中,我们展示了如何在 JavaScript 中使用 window.confirm。此方法对于创建简单的确认对话框和改善 Web 应用程序中的用户体验至关重要。

作者

我叫 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 JS DOM 教程