Jquery .each() -返回值未定义

Jquery .each() - return value undefined

本文关键字:返回值 未定义 each Jquery      更新时间:2023-09-26

为什么getColorOptionSelect()返回未定义的值(我确信它有一个值由调试器)。

这肯定是一个与范围相关的问题,抱歉我的js无知

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;
    }
});

getColorOptionSelect没有(未注释的)return语句

唯一的返回语句是在您传递给each()的匿名函数中。它将被each()下面的代码使用(如果它是false,它将停止循环)。

这不是作用域的问题,只是存在多个函数。

你可能想:

  • 在调用each()之前定义一个变量
  • 在每个循环中给它赋一个值
  • 返回getColorOptionSelect
  • 末尾的变量

你应该这样做:

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;
    }

在你的情况下,你正在做返回从回调函数传递给每个,它不会从getColorOptionSelect传递

你唯一能做的是从每个函数回调返回一个值是告诉jquery它是否应该去下一个项目(return true;)或不(return false;)

取消最后一条return语句的注释以返回一个值(如selId)

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 false;  //<---  return false to stop further propagation of each
        }
    });
      return selId; //<---  Must return something 
}
});