【问题标题】:JQuery droppable() does not recognize "this" object referenceJQuery droppable() 无法识别“this”对象引用
【发布时间】:2012-04-12 10:02:02
【问题描述】:

我有一个这样的对象:

function ImageHolder(Attributes, Parent)
{
    this.Id = Attributes['Id'];
    this.Parent = Parent;

    this.Element = $('<div/>');

        this.msg = "hello world";

    this.Parent.append(this.Element);


    this.handleDrop = function(e, ui)
    {
        alert(this.msg);

    };

    this.Element.droppable({drop: this.handleDrop});
}

然后我创建一个像这样的对象:

holder = new ImageHolder(A,B);

但是当我尝试将一些东西放到元素上时,我得到了这个错误:

this.msg is undefined

我在这里做错了吗?

【问题讨论】:

    标签: javascript jquery object droppable


    【解决方案1】:

    复制一份;

    var thisCopy = this;
    

    在下面的函数之前,然后像这样替换...

    this.handleDrop = function(e, ui)
    {
        alert(thisCopy.msg);
    
    };
    

    【讨论】:

    • this 在handleDrop 函数中是指handleDrop 函数本身,而不是它之外的对象。此外,thisCopy(你可以随意命名)是一个浅拷贝,因此它不会与同一页面上的其他对象冲突,并且会同时更新真实的this。因此,您可以在对象中的任何位置使用thisCopy
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-08
    • 1970-01-01
    相关资源
    最近更新 更多