一种使用方法confirm()是,当某些UI操作对页面进行了一些破坏性的更改时,最好将其与通知和用户确认一起显示-例如在删除帖子消息之前:
<div id="post-102"> <p>I like Confirm modals.</p> <a data-deletepost="post-102">Delete post</a> </div> <div id="post-103"> <p>That's way too cool!</p> <a data-deletepost="post-103">Delete post</a> </div>
// 收集所有按钮 var deleteBtn = document.querySelectorAll("[data-deletepost]"); function deleteParentPost(event) { event.preventDefault(); // 防止页面滚动在锚点单击时跳转 if( confirm("Really Delete this post?") ) { var post = document.getElementById( this.dataset.deletepost ); post.parentNode.removeChild(post); // 待办事项:从数据库中删除该帖子 } // 否则,什么都不做 } // 将点击事件分配给按钮 [].forEach.call(deleteBtn, function(btn) { btn.addEventListener("click", deleteParentPost, false); });
jsFiddle演示