js实现确认
实现确认对话框的方法
在JavaScript中,可以使用内置的confirm()函数或自定义模态框来实现确认功能。
使用confirm()函数
const result = confirm('确定要执行此操作吗?');
if (result) {
// 用户点击了确定
console.log('操作已确认');
} else {
// 用户点击了取消
console.log('操作已取消');
}
自定义确认对话框 通过HTML和CSS创建自定义样式,配合JavaScript实现更灵活的交互。
<div id="customConfirm" style="display:none;">
<div class="dialog-content">
<p>确定要删除吗?</p>
<button id="confirmYes">确定</button>
<button id="confirmNo">取消</button>
</div>
</div>
<script>
document.getElementById('confirmYes').addEventListener('click', function() {
console.log('操作已确认');
document.getElementById('customConfirm').style.display = 'none';
});
document.getElementById('confirmNo').addEventListener('click', function() {
console.log('操作已取消');
document.getElementById('customConfirm').style.display = 'none';
});
function showConfirm() {
document.getElementById('customConfirm').style.display = 'block';
}
</script>
使用Promise封装确认逻辑
对于异步操作,可以用Promise封装自定义确认对话框。
function customConfirm(message) {
return new Promise((resolve) => {
const dialog = document.createElement('div');
dialog.innerHTML = `
<div>${message}</div>
<button class="confirm-btn">确定</button>
<button class="cancel-btn">取消</button>
`;
dialog.querySelector('.confirm-btn').addEventListener('click', () => {
document.body.removeChild(dialog);
resolve(true);
});
dialog.querySelector('.cancel-btn').addEventListener('click', () => {
document.body.removeChild(dialog);
resolve(false);
});
document.body.appendChild(dialog);
});
}
// 使用示例
customConfirm('确认提交吗?').then(result => {
if (result) {
console.log('提交成功');
} else {
console.log('取消提交');
}
});
第三方库实现
流行的UI库如SweetAlert2提供了更美观的确认对话框。

// 需要先引入SweetAlert2库
Swal.fire({
title: '确认删除?',
text: "删除后无法恢复",
icon: 'warning',
showCancelButton: true,
confirmButtonText: '确定',
cancelButtonText: '取消'
}).then((result) => {
if (result.isConfirmed) {
Swal.fire('已删除', '', 'success');
}
});






