【问题标题】:Jquery events and objects?Jquery 事件和对象?
【发布时间】:2011-09-21 16:25:11
【问题描述】:

我正在尝试这样做:

var foo = new Foo();
foo.setEvents( foo );

foo 的代码:

function Foo()
{
   this.id = getId(); //this works successfully, each instance of foo gets
                          //assigned a new auto incrementing id e.g 1, 2, 3, etc

   this.setEvents = function( that ) 
   {
      $("#myButton").click( that.bar );
   }

   this.bar = function()
   {
      alert(this.id);
   }
}

每当我运行此代码并单击我的按钮时,我都会收到一条提示“未定义”的警报

当事件被触发时,如何保存我想要运行其方法的对象的状态?

【问题讨论】:

  • 你的句柄和头像让我想对这个问题投反对票。
  • @alex 他希望得到对象的 id 而不是按钮。
  • @kingjiv:哦,我明白了:)我回答了。
  • @KirkWoll:让我们看看我们是否可以将他投票到 30,000? :)

标签: javascript jquery oop jquery-events


【解决方案1】:

this 指的是 jQuerys 范围内不同的东西...

function Foo()
{
   obj=this;
   this.id = 1; //this works successfully, each instance of foo gets
                          //assigned a new auto incrementing id e.g 1, 2, 3, etc

   this.setEvents = function( that ) 
   {
      $("#myButton").click( that.bar );
   }

   this.bar = function()
   {
      console.log(obj)
   }
}
var foo = new Foo();
foo.setEvents( foo );

【讨论】:

    【解决方案2】:

    调用该函数时,this 指向处理该事件的本机 DOM 元素。

    您需要对可以在该函数范围内解析的对象本身的引用。

    执行此操作的常用方法是使用var that = this

    jsFiddle.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 2012-03-19
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      • 2015-01-27
      相关资源
      最近更新 更多