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

为什么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语句。

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

这不是范围问题,只是存在多个function。

你可能想:

  • 在调用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 } });