2013-01-21 88 views
1

爲什麼getColorOptionSelect()返回未定義的值(我確定它有一個調試器的值)。jquery .each() - 返回值undefined

這是肯定的有關範圍的問題,對不起我的無知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; 
    } 

}); 

回答

4

getColorOptionSelect沒有一個(未註釋)return聲明。

您擁有的唯一返回聲明是在您傳遞給each()的匿名函數中。它將被底層代碼each()消耗(如果它是false,將停止循環)。

這不是範圍問題,只是存在多個功能。

你可能想:

  • 定義一個變量,你叫each()
  • 一個值分配給它的每個循環中
  • 返回之前在getColorOptionSelect
2
結束變量

你應該這樣做:

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;

+0

謝謝你,這是工作的罰款 – WonderLand

1

取消對最後return語句retun值(類似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 
} 

}); 
+0

每個都不支持像那樣的返回,因此是錯誤。退出每個它需要返回false。 – epascarello