[英]jQuery this inside each loop
在initialize()
函數內部, each
循環都有一個jQuery。 在這個循環是一個參考this.dbcolumns
這顯然是無法正常運轉的jQuery的重新分配了this
電流回路的元素。 那么如何從循環內部引用this.dbcolumns
呢? 它在循環外工作正常。
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;
}
}
引用要保留在循環外部的“this”。
var self = this;
然后你可以在循環中使用“self”。
在each
回調之外存儲this
的引用,或使用ES5 bind
方法 :
$(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));
要解決的常見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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.