取消href中的功能

san*_*ers 3 jquery

我有一个类似的链接

<a href="www.site.com"  class="cancel">go there </a>
Run Code Online (Sandbox Code Playgroud)

然后我有一些jQuery:

$(".cancel").click(function(){
        confirm("sure??");
 });
Run Code Online (Sandbox Code Playgroud)

但是当我在警告框中单击取消时,它仍然会转到www.site.com而不是什么都不做.怎么解决这个?

Cha*_*ant 9

返回bool是旧方法,但不是每个浏览器中的首选方法,而且这些天我遇到了很多问题.jQuery包装事件对象并为您处理事件取消.

http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29

$(".cancel").click(function(event){
    if (!confirm("Sure??"))
       event.preventDefault();
});
Run Code Online (Sandbox Code Playgroud)


Ily*_*man 7

添加return语句:

$(".cancel").click(function(){
    return confirm("sure??");
});
Run Code Online (Sandbox Code Playgroud)