2012-06-17 95 views
2

initialize()函数里面有一个jQuery each循环。在那个循环中,对this.dbcolumns的引用显然不起作用,因为jQuery已经将当前循环元素重新分配为this。那么我如何从循环内部引用this.dbcolumns?它在循环外工作正常。jQuery这个每个循环里面

function datatable() { 
    this.url = ''; 
    this.htmltable = ''; 
    this.dbtable = ''; 
    this.dbcolumns = new Array(); 
    this.idfield = 'id'; 
    this.pageno = 0; 
    this.pagesize = 15; 
    this.totalpages = 0; 
    this.totalrecords = 0; 
    this.searchterm = ''; 

    this.initialize = function() { 
     this.dbtable = $(this.htmltable).attr('data-table'); 
     this.dbcolumns.push(this.idfield); 
     $(this.htmltable + ' th[data-field]').each(function(i, col){ 
      this.dbcolumns.push($(col).attr('data-field')); /* <<<<<<<<<< this line */ 
     }); 
     return this; 
    } 
} 
+1

'va r that = this' then use'that' ... – gdoron

+1

备注:函数表达式应该有一个尾随分号。 – pimvdb

+0

谢谢pimvdb。会做:) – Christian

回答

13

对您想要保留在循环外部的“this”进行引用。

var self = this; 

然后你可以在循环中使用“self”。

+0

谢谢!不过,标记为另一个11分钟的答案:s – Christian

4

商店each回调外this的引用,或使用ES5 bind method

$(this.htmltable + ' th[data-field]').each(function(i, col){ 
    this.dbcolumns.push($(col).attr('data-field')); 
}.bind(this)); 

或者,正如在评论中指出的使用$.proxy

$(this.htmltable + ' th[data-field]').each($.proxy(function(i, col){ 
    this.dbcolumns.push($(col).attr('data-field')); 
}, this)); 
+0

对于jQuery,使用'$ .proxy'可能是明智的,因为'.bind'在任何地方都不受支持。 – pimvdb

+0

是的。我最近在PrototypeJS上做了很多工作(为你绑定'bind'),所以我一直在混合使用jQuery模式和Prototype模式。 –

3

常见的JS模式来解决是用闭包:

this.initialize = function() { 
    var that = this; 

    this.dbtable = $(this.htmltable).attr('data-table'); 
    this.dbcolumns.push(this.idfield); 
    $(this.htmltable + ' th[data-field]').each(function(i, col){ 
     that.dbcolumns.push($(col).attr('data-field')); /* <<<<<<<<<< this line */ 
    }); 
    return this; 
}