jquery确认框
使用 jQuery 实现确认框
jQuery 可以通过 confirm() 方法或自定义模态框实现确认框功能。以下是几种常见实现方式:
原生 JavaScript confirm() 封装
if (confirm("确定要执行此操作吗?")) {
// 用户点击“确定”后的逻辑
console.log("操作已确认");
} else {
// 用户点击“取消”后的逻辑
console.log("操作已取消");
}
使用 jQuery UI 对话框
需引入 jQuery UI 库:
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
代码实现:
$("#dialog-confirm").dialog({
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"确定": function() {
$(this).dialog("close");
console.log("操作已确认");
},
"取消": function() {
$(this).dialog("close");
console.log("操作已取消");
}
}
});
HTML 结构:

<div id="dialog-confirm" title="确认操作">
<p>确定要执行此操作吗?</p>
</div>
使用 Bootstrap 模态框
需引入 Bootstrap:
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
代码实现:

$("#confirmModal").on("click", ".btn-confirm", function() {
console.log("操作已确认");
});
$("#confirmModal").on("click", ".btn-cancel", function() {
console.log("操作已取消");
});
HTML 结构:
<div class="modal fade" id="confirmModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">确认操作</h5>
</div>
<div class="modal-body">
<p>确定要执行此操作吗?</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary btn-cancel" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary btn-confirm" data-dismiss="modal">确定</button>
</div>
</div>
</div>
</div>
第三方插件 SweetAlert2
引入 CDN:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
调用示例:
Swal.fire({
title: "确认操作",
text: "确定要执行此操作吗?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "确定",
cancelButtonText: "取消"
}).then((result) => {
if (result.isConfirmed) {
console.log("操作已确认");
}
});
注意事项
- 原生
confirm()会阻塞浏览器线程,样式不可定制。 - jQuery UI 和 Bootstrap 方案需要加载额外库,但支持高度自定义。
- SweetAlert2 提供更美观的动画效果,但需引入独立插件。
根据项目需求选择合适方案,轻量级场景推荐原生 confirm(),复杂交互推荐 SweetAlert2 或 Bootstrap 方案。






