Scope of jQuery each() function?

痞子三分冷 提交于 2019-12-23 01:47:06

问题


I'm working with the jQuery ColorPicker widget - specifically exercising the ColorPickerSetColor function (just 'setColor' internally). Code excerpt:

        setColor: function(col) {
            if (typeof col == 'string') {
                col = HexToHSB(col);
            } else if (col.r != undefined && col.g != undefined && col.b != undefined) {
                col = RGBToHSB(col);
            } else if (col.h != undefined && col.s != undefined && col.b != undefined) {
                col = fixHSB(col);
            } else {
                return this;
            }
            return this.each(function(){
                if ($(this).data('colorpickerId')) {
                    var cal = $('#' + $(this).data('colorpickerId'));
                    cal.data('colorpicker').color = col;
                    cal.data('colorpicker').origColor = col;
                    fillRGBFields(col, cal.get(0));
                    fillHSBFields(col, cal.get(0));
                    fillHexFields(col, cal.get(0));
                    setHue(col, cal.get(0));
                    setSelector(col, cal.get(0));
                    setCurrentColor(col, cal.get(0));
                    setNewColor(col, cal.get(0));
                }
            });
        }

It seems that there is a bug in the widget. The 'col' parameter, when inspected inside of the each() call, is undefined. I've read the documentation and other examples, and everything I can find indicates that 'col' should still be in scope when the each() call executes the function, but it doesn't seem to be...

Help?

Thanks!


回答1:


Try defining another variable:

 setColor: function(xCol) {
     var col = xCol;
     // ...
 }

If that works, then there's a weirdness in the closure system when it comes to parameters to functions. That sort of behavior could be browser-specific.




回答2:


I just ended up using a temporary variable in a known-good scope (the parent of the setColor function). Definitely a hack, but it works. If anyone knows how to fix this the right way, please let me know. :)

Thanks! -Rich



来源:https://stackoverflow.com/questions/1397062/scope-of-jquery-each-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!