简体   繁体   English

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

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

I am trying to use bootbox with Twitter Bootsrap . 我正在尝试将Bootbox与Twitter Bootsrap一起使用。

In the code below when I use this.attr('href'); 在下面的代码中,当我使用this.attr('href'); and I get TypeError: this.attr is not a function . 我得到TypeError: this.attr is not a function

When I change to $(this).attr('href'); 当我更改为$(this).attr('href'); i get Undefined . 我得到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: 那不再是您的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));
});

The problem is that this or $(this) no longer is pointing to the link, but the bootbox -callback. 问题是this$(this)不再指向链接,而是指向bootbox This can fixed by storing the variable that $(this) is pointing to. 这可以通过存储$(this)指向的变量来解决。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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