且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将点击事件绑定到类中的方法

更新时间:2023-10-07 09:21:46

一种简单的方法来实现:

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

另一种方式,使用$.proxy:>

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

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

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