0

我在创建后找到了这段代码

<table> ... content ...
</ tables>

...我需要循环“FOR”之外的“j”的累积值...

var dt = $(".table thead th").length;
for (var i = 0; i < dt; ++i) {
    (function (j) {
        var dt = $(".table thead th").length;
        $(".table thead").each(function () {
            var $ths = $(this).find('th');
            if ($ths.length != 0 && $ths.eq(j).text() != "Estado" && $ths.eq(j).text() != "ESTADO" && $ths.eq(j).text() != "Acciones" && $ths.eq(j).text() != "ACCIONES") {
                j = j + ",";  // I need this value, the value to be displayed is something like this: 0,1,2,3 ...
                alert(j);
            }
        });
        return j;
    })(i);
}

/* I need the value of "j" here, but this does not work */
var variable = j;
alert(variable);
4

3 回答 3

3

像下面这样的东西应该可以工作:

var dt = $(".table thead th").length;
var variable = "";
for (var i = 0; i < dt; ++i) {
    variable += (function (j) {
        var dt = $(".table thead th").length;
        $(".table thead").each(function () {
            var $ths = $(this).find('th');
            if ($ths.length != 0 && $ths.eq(j).text() != "Estado" && $ths.eq(j).text() != "ESTADO" && $ths.eq(j).text() != "Acciones" && $ths.eq(j).text() != "ACCIONES") {
                j = j + ",";
                alert(j);
            }
        });
        return j;
    })(i);
}
alert(variable);

在您当前的代码j中,匿名函数正在返回但没有以任何方式使用它,在for循环内部,您需要通过在每次迭代中添加函数的返回值来执行累积。

作为旁注,在循环之外创建函数会更有效。

于 2013-11-01T16:16:32.463 回答
2

我想你正在寻找的是

var indexes = $(".table thead th").map(function (i) {
    var text = $.trim($(this).text());
    if (text && text != "Estado" && text != "ESTADO" && text != "Acciones" && text != "ACCIONES") {
        alert(i);
        return i;
    }
}).get().join(',')

甚至更短

var ignore = ["Estado", "ESTADO", "Acciones", "ACCIONES"]

var indexes = $(".table thead th").map(function (i) {
    var text = $.trim($(this).text());
    if (text && $.inArray(text, ignore) == -1) {
        alert(i);
        return i;
    }
}).get().join(',')
于 2013-11-01T16:17:00.410 回答
1

好的,快速而肮脏,基于您现有的代码。只需一项更改:

var variable;
var dt = $(".table thead th").length;
for (var i = 0; i < dt; ++i) {
    (function (j) {
        var dt = $(".table thead th").length;
        $(".table thead").each(function () {
            var $ths = $(this).find('th');
            if ($ths.length != 0 && $ths.eq(j).text() != "Estado" && $ths.eq(j).text() != "ESTADO" && $ths.eq(j).text() != "Acciones" && $ths.eq(j).text() != "ACCIONES") {
                j = j + ",";
                alert(j);
            }
        });
        variable += j;
        return j;
    })(i);
}

alert(variable);
于 2013-11-01T16:16:52.783 回答