Jquery .each() - return value undefined

前端 未结 3 502
慢半拍i
慢半拍i 2020-12-12 04:51

Why getColorOptionSelect() return undefined value (I\'m sure it has a value by debugger ).

It is for sure an issue related to the scope, sorry for my js ignorance

3条回答
  •  甜味超标
    2020-12-12 05:28

    You should do:

    function getColorOptionSelect() {
    
            // get label
            var selId;
            jQuery(".product-options dl label").each(function () {
                el = jQuery(this);
                // lower case, remove *
                var labelText = el.text().toLowerCase().replace("*", "");
                if (labelText == 'color') {
                    //return element
                    selId = el.parent().next().find("select").attr('id');
                    return false; // to stop further execution of each
                }
            });
            return selId;
        }
    

    In your case you are doing return from callback function passed to each and it will not be passed from getColorOptionSelect

    The only thing you can do returning a value from each function callback is to tell jquery if it should go to next item (return true;) or not (return false;)

提交回复
热议问题