簡體   English   中英

在每個循環中jQuery這個

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM