简体   繁体   中英

Jquery a href onclick to controller without reload page

I am trying to write a code that includes confirm message by using jquery.

İf ı click to Exit according to my below code occurs reload of my page.

<a href="Exit" onclick="return confirm('Are you sure you want to exit?')">Exit</a>

How can ı write above code without reload page with confirm message in Jquery ?

İf confirm ok = go to href (without reload) İf confirm cancel = cancel it,

Try the following code

<a href="#Exit" onclick="return confirm('Are you sure you want to exit?'); return false">Exit</a>

Explanation:

# A URL fragment is a name preceded by a hash mark (#), which specifies an internal target location (an ID) within the current document.

While return false is a way to tell the event to not actually fire.

See Demo

I use this function to do something like that :

function confirm_text_url(message, url){
    var response = confirm(message);
    if (response==true)
    {
        document.location.href=url;
    }
}

Your posted code will obviously already work, but since you've asked for it this is the same thing, but using jQuery to assign the event handler...

HTML

<a href="Exit" id="exit-link">Exit</a>

Javascript

$(function() {
    $("#exit-link").on("click", function() {
        return confirm("Are you sure you want to exit?");
    });
});

I added an ID to the link, just to be able to explicitly reference it using jQuery. Other than that it's the same thing.

from the text in your confirm I guess you might be looking for this: How to show the "Are you sure you want to navigate away from this page?" when changes committed?

or dicussed in more detail regarding support for older browsers: How to show the "Are you sure you want to navigate away from this page?" when changes committed?

You will have to evaluate the result

ex:

var r=confirm("Are you sure you want to exit?");
if (r==true)
  {
  x="You pressed OK!";
  }
else
  {
  x="You pressed Cancel!";
  }

in your case, it would be something like:

<a href="javascript:void(0);" onclick="confirm('Are you sure you want to exit?') ? window.location = 'page-to-go-to': return ">Exit</a>

Also, use javascript:void(0); as the href, so you're sure the default propagation is not triggered

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM