将click事件绑定到类中的方法

时间:2021-11-22 20:31:01

In the constructor of my object, I create some span tag and I need to refers them to a method of the same object.

在我的对象的构造函数中,我创建了一些span标记,我需要将它们引用到同一对象的方法中。

Here is an example of my code:

以下是我的代码示例:

$(document).ready(function(){
    var slider = new myObject("name");
});

function myObject(data){
    this.name = data;

    //Add a span tag, and the onclick must refer to the object's method
    $("body").append("<span>Test</span>");
    $("span").click(function(){
        myMethod(); //I want to exec the method of the current object
    }); 


    this.myMethod = myMethod;
    function myMethod(){
        alert(this.name); //This show undefined
    }

}

With this code the method is called, but it is not a reference to the object (this.name show undefined) How can I resolve that?

使用此代码调用该方法,但它不是对象的引用(this.name show undefined)我该如何解决?

Thanks a lot!

非常感谢!

1 个解决方案

#1


6  

One simple way to achieve that:

实现这一目标的一种简单方法:

function myObject(data){
    this.name = data;

    // Store a reference to your object
    var that = this;

    $("body").append("<span>Test</span>");
    $("span").click(function(){
        that.myMethod(); // Execute in the context of your object
    }); 

    this.myMethod = function(){
        alert(this.name); 
    }
}

Another way, using $.proxy:

另一种方法,使用$ .proxy:

function myObject(data){
    this.name = data;

    $("body").append("<span>Test</span>");
    $("span").click($.proxy(this.myMethod, this)); 

    this.myMethod = function(){
        alert(this.name); 
    }
}

#1


6  

One simple way to achieve that:

实现这一目标的一种简单方法:

function myObject(data){
    this.name = data;

    // Store a reference to your object
    var that = this;

    $("body").append("<span>Test</span>");
    $("span").click(function(){
        that.myMethod(); // Execute in the context of your object
    }); 

    this.myMethod = function(){
        alert(this.name); 
    }
}

Another way, using $.proxy:

另一种方法,使用$ .proxy:

function myObject(data){
    this.name = data;

    $("body").append("<span>Test</span>");
    $("span").click($.proxy(this.myMethod, this)); 

    this.myMethod = function(){
        alert(this.name); 
    }
}