Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

javascript - Jquery .each() - return value undefined

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

jQuery(document).ready(function () {

    colorSelectID = getColorOptionSelect();
    alert(colorSelectID);

    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 selId;
            }
        });
        //    return null;
    }

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

getColorOptionSelect doesn't have an (uncommented) return statement.

The only return statement you have is inside the anonymous function you pass to each(). It will be consumed by the code underlying each() (which will stop looping if it is false).

This isn't a problem of scope, just of there being multiple functions.

You probably want to:

  • define a variable before you call each()
  • assign a value to it inside the each loop
  • return that variable at the end of getColorOptionSelect

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...