$(this).attr("href")返回undefined

Oua*_*lid 1 javascript jquery twitter-bootstrap bootbox

我正在尝试使用Twitter Bootsrap的bootbox.

在我使用的下面的代码中this.attr('href');,我得到了TypeError: this.attr is not a function.

当我改变到$(this).attr('href');我得到Undefined.

 <a class="alert" href="list_users.php?id=123">Delete user</a>

 <script src="bootbox.min.js"></script>
    <script>
    $(document).on("click", ".alert", function(e) {
        e.preventDefault();

        bootbox.confirm("Are you sure?", function(result) {

        if (result) {
            document.location.href = this.attr('href'); // doesn't work
            document.location.href = $(this).attr('href'); // Undefined
        }               
    });

    });
</script>
Run Code Online (Sandbox Code Playgroud)

任何的想法?

Esa*_*ija 7

这不再是你的jQuery事件回调函数,而是bootbox回调...尝试$.proxy绑定上下文:

$(document).on("click", ".alert", function(e) {
    e.preventDefault();

    bootbox.confirm("Are you sure?", $.proxy(function(result) {
        if (result) {
            document.location.href = this.href;
        }
    }, this));
});
Run Code Online (Sandbox Code Playgroud)