js实现确认
实现确认弹窗的方法
在JavaScript中,确认弹窗可以通过内置的confirm()函数实现。该函数会显示一个带有指定消息和"确定"/"取消"按钮的对话框。
let result = confirm("您确定要执行此操作吗?");
if (result) {
// 用户点击了"确定"
console.log("操作已确认");
} else {
// 用户点击了"取消"
console.log("操作已取消");
}
自定义确认对话框
如果需要更美观的确认对话框,可以创建自定义模态框:
<div id="customConfirm" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000;">
<div style="background:white; width:300px; margin:100px auto; padding:20px; border-radius:5px;">
<p id="confirmMessage">确认执行此操作吗?</p>
<button id="confirmOk">确定</button>
<button id="confirmCancel">取消</button>
</div>
</div>
<script>
function showConfirm(message, callback) {
const dialog = document.getElementById('customConfirm');
const msg = document.getElementById('confirmMessage');
msg.textContent = message;
dialog.style.display = 'block';
document.getElementById('confirmOk').onclick = function() {
dialog.style.display = 'none';
callback(true);
};
document.getElementById('confirmCancel').onclick = function() {
dialog.style.display = 'none';
callback(false);
};
}
// 使用示例
showConfirm("确认删除此项吗?", function(result) {
if(result) {
console.log("删除操作已确认");
} else {
console.log("删除操作已取消");
}
});
</script>
使用第三方库实现确认
流行的UI库如SweetAlert2提供了更强大的确认对话框功能:
// 引入SweetAlert2库后
Swal.fire({
title: '确认操作',
text: "您确定要执行此操作吗?",
icon: 'warning',
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消'
}).then((result) => {
if (result.isConfirmed) {
console.log("操作已确认");
}
});
Promise风格的确认实现
现代JavaScript可以使用Promise封装确认逻辑:
function confirmPromise(message) {
return new Promise((resolve) => {
const result = confirm(message);
resolve(result);
});
}
// 使用示例
confirmPromise("确认提交表单吗?")
.then(confirmed => {
if(confirmed) {
document.getElementById('myForm').submit();
}
});
每种方法适用于不同场景,内置confirm()简单快捷,自定义对话框提供更好的用户体验,第三方库提供丰富的功能,Promise风格适合现代异步编程。







