And*_*zos 27 html javascript jquery
我的HTML中有一个链接:
<a href="/DoSomethingDangerous">do something dangerous</a>
Run Code Online (Sandbox Code Playgroud)
访问DoSomethingDangerous链接会导致不容易发生可逆操作.
因此,在点击链接后,我想要一个对话框(例如"你确定吗?""确定""取消"),如果用户点击取消,则不访问链接,浏览器仍然在同一页面.
使用Javascript或jQuery实现这个的最干净的技术是什么?
xda*_*azz 71
<a class="confirm" href="/DoSomethingDangerous">do something dangerous</a>
Run Code Online (Sandbox Code Playgroud)
JavaScript的:
$(function() {
$('.confirm').click(function(e) {
e.preventDefault();
if (window.confirm("Are you sure?")) {
location.href = this.href;
}
});
});
Run Code Online (Sandbox Code Playgroud)
甚至更简单:
$(function() {
$('.confirm').click(function() {
return window.confirm("Are you sure?");
});
});
Run Code Online (Sandbox Code Playgroud)
无法设置原生确认框的样式.如果你想要风格,那么你可以使用jQuery.UI.dialog
CoR*_*CoR 33
如果我们知道DOM函数在"是"和"否" 上window.confirm()返回布尔值,我们的链接可以简化一点:truefalse
<a href="/DoSomething" onclick="return confirm('Are you sure?');">Link</a>
Run Code Online (Sandbox Code Playgroud)
小智 19
我认为最简单的解决方案是
<a href="/DoSomethingDangerous" onclick="if (!confirm('Are you sure?')) return false;">Link test</a>
web*_*per 14
$('a').click(function(e)
{
if(confirm("Are you sure?"))
{
alert('navigate!');
}
else
{
e.preventDefault();
}
});
Run Code Online (Sandbox Code Playgroud)