jQuery的每个循环内 [英] jQuery this inside each loop

查看:80
本文介绍了jQuery的每个循环内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

initialize()函数内部,有一个jQuery each循环.在该循环内是对this.dbcolumns的引用,由于jQuery已将this重新分配给当前循环元素,因此该参考显然不起作用.那么如何从循环内部引用this.dbcolumns?它可以在循环之外正常工作.

Inside the initialize() function there is a jQuery each loop. Inside that loop is a reference to this.dbcolumns which is obviously not working as jQuery has reassigned this to the current loop element. So how can I reference this.dbcolumns from inside the loop? It works outside the loop ok.

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".

make a reference to the "this" that you want to hold onto outside of the loop.

var self = this;

然后您可以在循环中使用"self".

then you can use "self" inside the loop.

这篇关于jQuery的每个循环内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆