+ -
当前位置:首页 → 问答吧 → 事件代码中this的问题

事件代码中this的问题

时间:2009-10-16

来源:互联网

复制代码
  1. $(document).ready(function(){
  2.     var demo = new Demo();
  3.     demo.Init();
  4. });
  5. //封装的类
  6. function Demo(){
  7.     var obj = $("<div style='cursor:pointer;border:1px solid #515152; width:210px; height:25px; font-size:12px; color:#c4c4c4;'>单击我呀</div>");
  8.     this.Init = function(){
  9.         $(document.body).append(obj);
  10.         $(obj).click(function(){
  11.             alert("被单击了!");
  12.             this.Show();   //这里出错了,Show方法没有被调用
  13.         });
  14.     }
  15.     
  16.     this.Show=function(){
  17.         alert("Show方法被调用");
  18.     }
  19. }


我想在单击时间中调用Show方法,应该怎么解决??

作者: wuyou331   发布时间: 2009-10-16

try it
复制代码
  1. $(document).ready(function(){
  2.     var demo = new Demo();
  3.     demo.Init();
  4. });
  5. //封装的类
  6. function Demo(){
  7.     var _this = this;
  8.     var obj = $("<div style='cursor:pointer;border:1px solid #515152; width:210px; height:25px; font-size:12px; color:#c4c4c4;'>单击我呀</div>");
  9.     this.Init = function(){
  10.         $(document.body).append(obj);
  11.         $(obj).click(function(){
  12.             alert("被单击了!");
  13.             _this.Show();   //这里出错了,Show方法没有被调用
  14.         });
  15.     }
  16.     
  17.     this.Show=function(){
  18.         alert("Show方法被调用");
  19.     }
  20. }

作者: getcase   发布时间: 2009-10-17