繁体   English   中英

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

[英]$(this).attr(“href”) return undefined

我正在尝试将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;
    }               
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM