开发者

jquery/javascript cancel link redirecting in if statement

I am trying to make a button that redirects only if a user confirms it. This is what I have so far.

Javascript:

function del_list(){
    doIt=confirm('do you wish to proceed?');
    if(doIt){
      //DO SOMETHING
    }
    else{
      //DON'T DO SOMETHING开发者_运维问答
    }
  }

HTML:

<a href=""><img src="icon.png" onclick="del_list()" border="0"></a>

Currently the page redirects whether the user confirms or not. I only want the page to redirect if the user confirms (clicks ok on the confirm popup).


If you want the onclick event to be cancelled, you'll want to use preventDefault on the event itself or you can return false. You could modify your code to look something like this:

function del_list(){
    doIt=confirm('do you wish to proceed?');
    if(doIt){
      //DO SOMETHING
    }
    else{
      return false;
    }
  }

HTML

<a href=""><img src="icon.png" onclick="return del_list()" border="0"></a>


function del_list(){
    doIt=confirm('do you wish to proceed?');
    if(!doIt){
      return false;
    }

}

If the user does not confirm, we prevent the default action of the browser.


function del_list(){
    doIt=confirm('do you wish to proceed?');
    if(doIt){
      //DO SOMETHING
    }
    else{
      return false;
    }
  }


I would use a callback, since javascript is Asynchronous you are not going to block with that confirm:

function confirm(msg, callback) {
    $('#msg').text(msg);
    $('#yes').click(callback);
    $('#dialog').dialog();
}

$('#button').click(function() {
    confirm('Do It?', action);
});

function action() {
    alert('Action!');
}


First place why do you have anchor enclosing a img if you want to return false when user says no. When user says yes you want to do something and I believe you dont have to redirect to the href set in the anchor.

I think you should remove the anchor everything should be fine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜