【问题标题】:jquery "this" binding issue on event handler (equivalent of bindAsEventListener in prototype)事件处理程序上的 jquery“this”绑定问题(相当于原型中的 bindAsEventListener)
【发布时间】:2010-05-19 09:49:04
【问题描述】:

在 jquery 中,事件处理程序的绑定是事件生成 DOM 元素(这指向 dom 元素)。 在原型中更改事件处理程序的绑定可以使用bindAsEventListener 函数; 如何从事件处理程序访问实例和 DOM 元素?
类似于How can I bind an event handler to an instance in JQuery?

function Car(){
    this.km = 0;
    $("#sprint").click(this.drive); //setup event handler
}

// event handler
// in it I need to access both the clicked element
// and the binding object (instance of car)
Car.prototype.drive = function(){
    this.km += 10; // i'd like to access the binding (but jq changes it)
    this.css({ // also the element
        left: this.km 
    }); 
    // NOTE that is inside this function I want to access them not elsewhere
}

var car = new Car();

【问题讨论】:

    标签: javascript jquery events binding this


    【解决方案1】:

    嗯,也许你可以使用 jQuery.proxy()?

    http://api.jquery.com/jQuery.proxy/

    【讨论】:

      【解决方案2】:

      只需将变量绑定到this 并使用它。

      function Car(){
          this.km = 0;
          var that = this;
          $("#sprint").click(function(){
               that.drive(this);
          });
      }
      
      
      Car.prototype.drive = function(element){
          this.km += 10; // i'd like to access the binding (but jq changes it)
          this.css({ // also the element
              left: this.km 
          }); 
          alert(element.innerHTML);
          // NOTE that is inside this function I want to access them not elsewhere
      }
      

      处理程序将元素传递给实例

      【讨论】:

      • 我认为这可以自己解决 :) 但我更新了答案,说明如何访问类实例和元素
      • 另一个问题也有这种答案,但我觉得它很丑。这是在 jquery 社区中建议的方法吗?必须有更好的东西......或者只是个人品味的问题。我会让这个再烤一些,可能会接受你的回答。
      • 侦听器可能会收到一个event 对象,其中包含对触发事件的element 的引用,您可能会使用它。但我不确定我觉得哪个最丑..
      • 是的,但问题是我失去了对当前对象的引用(因为 this swich)我可以通过 event.currentTarget 获得的元素
      • this 绑定到范围,因此为了让 this 指向正确的范围,那么您需要在 ' 的左侧有正确的对象。运算符,否则您将不得不使用 .call.apply 将范围应用于您要调用的函数。最简单的方法是通过引入像that 这样的范围变量来将正确的对象保留在左侧。
      【解决方案3】:

      this 的值否则将指向(即,处理程序附加到的元素)也传递到事件对象的currentTarget 属性中。所以,如果你使用你所说的绑定函数:

      Car.prototype.drive = function(e) {
          // this will be your car object
          // e.currentTarget will be the element that you attached the click handler to
      }
      

      【讨论】:

      • 我不能使用bindAsEventListener,因为它来自原型。
      【解决方案4】:

      好的,你来了:

      var car = {km:0};
      $("#sprint").click(function(){
          car.km += 10;
          $(this).css({ left: car.km });
      });
      

      我尚未对其进行测试,但应该直截了当,或者至于你出错的地方是在你的“this”上,它正在查看“sprint”元素而不是“car”对象。

      【讨论】:

      • 这正是我想要避免的 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-22
      • 2010-10-22
      • 1970-01-01
      • 2011-03-28
      • 2011-01-24
      • 2011-08-09
      • 2016-04-17
      相关资源
      最近更新 更多