【问题标题】:How assign value to a namespace object variable if it is get it inside a jquery on click definition如果在单击定义时在 jquery 中获取命名空间对象变量,如何为其赋值
【发布时间】:2013-01-27 08:23:29
【问题描述】:

我想知道如何在 jquery 绑定中保存一个值,当它位于命名空间内时。

var obj = obj || (obj ={ 
    valuetosave:-1,
    init:function(){
        $("some selector").on("click",function(){
            tmpval = I get some value here
            how can asign 'tmpval' to obj.valuetosave if I can't use this because 
            is in the jquery scope
        })
    }
})

我知道无论是标题还是我的小描述都没有多大用处,希望小例子能说明我的问题。

谢谢

【问题讨论】:

    标签: jquery javascript-namespaces


    【解决方案1】:

    如果你想引用obj 的当前实例,那么你应该使用this 关键字。 例如

    var obj = obj || ({ 
      valuetosave:-1,
      init:function(){
    
        var self = this;  // preserver your global instance in a variable
          $("#mybutton").on("click",function(){               
              var tmpval = 'I get some value here'
              // here `this` refers to  the function event instance , not obj instance
              // So i am using self (which is global instance variable)
              self.valuetosave = tmpval;
              alert(self.valuetosave);
          });
      }
    });
    

    如果您需要更多帮助,请告诉我,请查看jsfiddle 链接。

    【讨论】:

      猜你喜欢
      • 2013-03-10
      • 2017-08-08
      • 1970-01-01
      • 2013-02-11
      • 2012-06-12
      • 2018-10-08
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多