-->

Calling href in Callback function

2019-08-30 00:21发布

问题:

I have a anchor tag in my page for logout.

<a href="/logout/" id="lnk-log-out" />

Here I am showing a Popup for confirmation with jQuery UI dialog.

If user click Yes from dialog it has to execute the link button's default action, I mean href="/logout".

If No clicked a Popup box should be disappeared.

jQuery Code

 $('#lnk-log-out').click(function (event) {
            event.preventDefault();
            var logOffDialog = $('#user-info-msg-dialog');

            logOffDialog.html("Are you sure, do you want to Logout?");
            logOffDialog.dialog({
                title: "Confirm Logout",
                height: 150,
                width: 500,
                bgiframe: true,
                modal: true,
                buttons: {
                    'Yes': function () {
                        $(this).dialog('close');
                        return true;
                    },
                    'No': function () {
                        $(this).dialog('close');
                        return false;
                    }
                }
            });

        });
    });

The problem is I am not able to fire anchor's href when User click YES.

How can we do this?

Edit: Right now I managed in this way

'Yes': function () {
                        $(this).dialog('close');
                        window.location.href = $('#lnk-log-out').attr("href");
                    }

回答1:

In the anonymous function called when 'Yes' is fired, you want to do the following instead of just returning true:

  1. Grab the href (you can get this easily using $('selector').attr('href');)
  2. Perform your window.location.href to the url you grabbed in point 1

If you want the a tag to just do it's stuff, remove any preventDefault() or stopPropagation(). Here I have provided two different ways :)

Don't use document.location, use window.location.href instead. You can see why here.

Your code in the 'Yes' call should look something like, with your code inserted of course:

'Yes': function () {
            // Get url
            var href = $('#lnk-log-out').attr('href');
            // Go to url
            window.location.href = href;
            return true; // Not needed
     }, ...

Note: Thanks to Anthony in the comments below: use window.location.href = ... instead of window.location.href(), because it's not a function!



回答2:

I have used this in many of my projects so i suggest window.location.href

'Yes': function () {
                        $(this).dialog('close');
                         window.location.href="your url"    
                        return true;
                    },