質問

I am trying to use bootbox with Twitter Bootsrap.

In the code below when I use this.attr('href'); and I get TypeError: this.attr is not a function.

When I change to $(this).attr('href'); i get 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>

Any idea?

役に立ちましたか?

解決

That's not your jQuery event callback function anymore, but the bootbox callback... try $.proxy to bind the context:

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

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

他のヒント

The problem is that this or $(this) no longer is pointing to the link, but the bootbox-callback. This can fixed by storing the variable that $(this) is pointing to. Note that this is also considered good practice if you are using the same object multiple times.

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

    var obj = this;

    bootbox.confirm("Are you sure?", function(result) {
    if (result) {
        document.location.href = obj.href;
    }               
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top