for循环将变量传递给函数

时间:2013-04-29 13:40:36

标签: jquery loops css-selectors

$(function () {
    $max = 4;
    $i = 1;
    for ($i = 1; $i < 3; $i++) {
        $('#itemListLeading table tr :nth-child(' + $i + ')').each(function () {
            $length = $(this).children().text().length;
            if ($length > $max) {
                $max = $length;
            }
            $('#itemListLeading table tr :nth-child(' + $i ' +)').promise().done(function () {
                $(this).css("min-width", $max * 8 + "px");
            });
        });
    };
});

不确定为什么这里不起作用。我试图传递'1'和'2',或许更晚一些传递给nth-child()。它适用于单个第n个孩子(1),即。没有for循环。或者有更好的方法来传递x量的变量来运行函数吗?

Here is a fiddle

1 个答案:

答案 0 :(得分:0)

您的脚本中出现语法错误:

$(function () {
    $max = 4;
    $i = 1;
    for ($i = 1; $i < 3; $i++) {
        $('#itemListLeading table tr :nth-child(' + $i + ')').each(function () {
            $length = $(this).children().text().length;
            if ($length > $max) {
                $max = $length;
            }
            // Old line
            //$('#itemListLeading table tr :nth-child(' + $i ' +)').promise().done(function () {

            $('#itemListLeading table tr :nth-child(' + $i + ')').promise().done(function () {
                $(this).css("min-width", $max * 8 + "px");
            });
        });
    };
});
相关问题