JSHint错误不要在循环内创建函数 [英] JSHint error Don't make functions within a loop

查看:72
本文介绍了JSHint错误不要在循环内创建函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过JSHint运行一些代码,但不断出现以下错误:

I'm running some code through JSHint and I keep getting the following error:

不要在循环中创建函数.

Don't make functions within a loop.

我尝试关闭关于循环内函数"的警告,这无助于阻止错误的报告.我已经决定使用JSHint的建议在此处重构代码, http://www.jshint.com/options/,但仍然出现错误.我希望有人可以帮助我稍微重构一下此代码,使其通过.这是该函数的副本:

I tried turning off the warning for 'About functions inside loops' off which does nothing to stop the error from being reported. I have decided to refactor the code, using JSHint's suggestions here, http://www.jshint.com/options/ but I'm still getting the error. I was hoping that somebody could help me to refactor this code slightly so it will pass. Here's a copy of the function:

function setSounds(parent) {
    var i,
        l;

    parent.getElements('.sound').each(function (elem) {
        var soundEvents = [];

        if (elem.get('fk_click_sound')) {
            soundEvents.push('click');
        }

        if (elem.get('fk_mouseover_sound')) {
            soundEvents.push('mouseenter');
        }

        if (soundEvents.length !== 0) {
            for (i = 0, l = soundEvents.length; i < l; i += 1) {
                elem.addEvent(soundEvents[i], (function () {
                    return function (e) {
                        FKSoundAIR(FKSoundStd[this.get('fk_' + e.type + '_sound')]);
                    };
                })(elem), false);
            }
        }
    });
}

我正在使用MooTools.此函数的目的是传递父元素,然后将声音事件应用于所有具有声音"类的子级.我正在使用自定义HTML属性(例如"fk_click_sound")向该函数提供其他信息.我从 http: //blog.jbrantly.com/2010/04/creating-javascript-function-inside.html .

I'm using MooTools. The purpose of this function is to pass a parent element and then apply sound event to all of the children with the class 'sound.' I'm using custom HTML attributes, such as 'fk_click_sound' to feed additional information to the function. I picked up this method of assigning a function within a loop from http://blog.jbrantly.com/2010/04/creating-javascript-function-inside.html.

您可以向我提出的任何建议或资源都很棒.谢谢!

Any suggestions or resources that you can point me to would be great. Thanks!

推荐答案

您可以尝试执行以下操作:

You can try something like this:

function make_handler(div_id) {
    return function () {
        alert(div_id);
    }
}
for (i ...) {
    div_id = divs[i].id;
    divs[i].onclick = make_handler(div_id);
}

这篇关于JSHint错误不要在循环内创建函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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