【问题标题】:Bind a click event to a method inside a class将点击事件绑定到类中的方法
【发布时间】:2013-06-21 13:54:05
【问题描述】:

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

这是我的代码示例:

$(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
    }

}

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

非常感谢!

【问题讨论】:

  • 它是因为this 指的是当前范围(这将是触发它的事件,即点击)

标签: javascript jquery class binding click


【解决方案1】:

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

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

【讨论】:

  • 或者我们可以只使用data 而不是this.name
  • @GokulKav 或 $.proxy,正如我刚刚添加的那样。或者绑定。有多种解决方案
  • @GokulKav 谢谢。为什么不使用data 添加答案?很高兴有多个答案显示不同的选项。
  • 我在课堂上试过这个,它没有绑定到点击事件,它只是在文档加载时执行该方法。
猜你喜欢
  • 1970-01-01
  • 2011-05-18
  • 2012-03-10
  • 1970-01-01
  • 2018-11-24
  • 1970-01-01
  • 2013-02-18
  • 2015-01-29
  • 1970-01-01
相关资源
最近更新 更多