jQuery'this'范围在事件处理程序中

时间:2014-04-16 12:36:15

标签: javascript jquery javascript-events event-handling this

我无法在对象的事件处理程序中访问父对象!!

我正在创建一个小部件:

(function( $ ) {

  $.widget('cs.window',{

     _create:function(){
       var me = this;
       this.append('<div class="close">X</div>');
       var close = this.element.find('.close');
       close.bind('click',function(){
        alert($(this));// this is referring event handler here
                       //but how to access `me` object here
        me.element.hide();//I want to achieve this, about but its saying me is undefined
      });
     }
  });

}(jQuery));

如何在点击事件处理程序中使用me对象?

1 个答案:

答案 0 :(得分:1)

如果使用this._on绑定函数,则回调内的this就是窗口小部件本身。尝试:

this._on(close, {
    click: function(){ this.element.hide(); }
});