$(this).attr("href")返回未定义

$(this).attr("href") return undefined

本文关键字:quot 返回 未定义 href attr this      更新时间:2023-09-26

我正在尝试使用bootbox与Twitter Bootsrap。

在下面的代码中,当我使用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>

任何想法?

这不再是你的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));
});

问题是this$(this)不再指向链接,而是bootbox -回调。这可以通过存储$(this)所指向的变量来修复。注意,如果多次使用同一个对象,这也被认为是良好的实践。

$(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;
    }               
});