【问题标题】:jslint error..Don't make functions within a loopjslint错误..不要在循环中创建函数
【发布时间】:2014-08-17 12:49:21
【问题描述】:

在下面的代码中,我收到了 JSLint 错误(不要在循环中创建函数)。你能帮我修改代码以满足JSLint吗?

setEllipsis : function () {
    $('.co_documentReportTable > thead > tr > th').each(function() {
        $(this).find('.co_dcrTable_Header').each(function() {
            var $el = $(this);
            if($el.css("overflow") === "hidden") {
                var text = $el.html();
                while ($el.height() > 64) {
                    $el.text(function (index, text) {
                        return text.replace(/\W*\s(\S)*$/, '...');
                    });
                    //
                    var txt = 'Fair consideration/no fraudulent conveyance';
                    if(text.indexOf(txt) !== -1 ) {
                        $el.text(txt + '...');
                    }
                }
            }
        });
    });
}

我尝试创建另一个函数并调用它,在这种情况下,while 循环将永远执行。

【问题讨论】:

  • 这适用于多行及以上代码工作,但出现 jslint 错误如何解决 jslint 错误?
  • 在 SO 上搜索 [javascript] closure loop
  • 只需禁用该规则。它在这里几乎不适用。

标签: javascript jquery jslint


【解决方案1】:

通常看起来您想在此处使用 text-overflow: ellipses CSS 属性。

否则 - 拉起匿名函数并为其命名,因此您最终可能会得到:

setEllipsis : function () {
    var addEllipses = function(index, text) {
        return text.replace(/\W*\s(\S)*$/, '...');
    };

    $('.co_documentReportTable > thead > tr > th').each(function() {
        $(this).find('.co_dcrTable_Header').each(function() {
            var $el = $(this);
            if($el.css("overflow") === "hidden")
            {
                var text = $el.html();
                while ($el.height() > 64) {
                    $el.text(addEllipses);
                    var txt = 'Fair consideration/no fraudulent conveyance';
                    if(text.indexOf(txt) !== -1 ){
                        $el.text(txt + '...');
                    }
                }
            }           
        });
    });
}

【讨论】: