Calling href in Callback function

守給你的承諾、 提交于 2019-12-11 18:27:10

问题


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;
                    },


来源:https://stackoverflow.com/questions/14977496/calling-href-in-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!