jQuery单击Event PreventDefault

Jus*_*tin 7 javascript

如果我有一个a标签:

<a id="delete-event" href="/delete/1234">Delete</a>
Run Code Online (Sandbox Code Playgroud)

还有一些提示确认删除的javascript:

 $("#delete-event").click(function(e) {
    e.preventDefault();

    bootbox.confirm("Are you sure you wish to delete this?", function(confirmed) {
        if(confirmed) {
            return true;
        }
    }); 
});
Run Code Online (Sandbox Code Playgroud)

我以为做e.preventDefault()会阻止a href射击,但事实并非如此.当我点击一个标签时,它只是转到网址,而不执行javascript.我怎样才能做到这一点?

谢谢.

sac*_*een 15

此代码有效:

你不能只是这样做,return true并期望在你完成之后链接开火e.preventDefault().我不得不bootbox.confirm()用JS确认替换你的,但它仍然可以工作.

$("#delete-event").click(function(e) {
    e.preventDefault();
    var a = confirm("yes?");
    if(a) window.location = $('#delete-event').attr('href');
});?
Run Code Online (Sandbox Code Playgroud)

DEMO

尝试用我上面提供的代码块替换你的代码块.如果可以,请将您的bootbox确认放回原处并重试.那会告诉你错误在哪里.


SMa*_*hew 6

最好只在需要时防止它.例如,如果用户从确认框中选择"取消",则阻止默认值.

$("#delete-event").click(function(e) {
    if (!confirm('Are you sure you wish to delete this?')) {
        e.preventDefault();
    } 
});?
Run Code Online (Sandbox Code Playgroud)

演示:http://jsfiddle.net/SCCDX/

通常,当您需要确认时,这是实现它的最佳方式,并且在提交表单之前,它对确认更​​有用.

当您要求确认时,我不确定bootbox是否会复制浏览器的行为.所以它可能在这种情况下不起作用.如果是这种情况,更好的方法是在某处设置标志.

$("#delete-event").click(function(e) {
    if (!$(this).data('confirmed')) {
       e.preventDefault()
    } else {
       bootbox.confirm("Are you sure you wish to delete this?", function(confirmed) {
          if(confirmed) {
              $(this).data('confirmed', 1).click();           
          }
       });        
    }
});?

// Disclaimer: This code is untested. clicking on the link may cause data loss. lol 
Run Code Online (Sandbox Code Playgroud)

不知何故,我不喜欢window.location方法,因为它可能导致附加到此元素的任何其他事件失败.