本文介绍了Jquery .each() - 返回值未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么getColorOptionSelect()返回未定义的值(我确定它有调试器的值)。
Why getColorOptionSelect() return undefined value (I'm sure it has a value by debugger ).
这肯定是与范围相关的问题,对不起对于我的js无知
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;
}
});
推荐答案
getColorOptionSelect
没有(未注释的)返回
语句。
getColorOptionSelect
doesn't have an (uncommented) return
statement.
你唯一的返回语句是您传递给每个()
的匿名函数。它将被底层每个()
的代码消耗(如果它是 false
,它将停止循环)。
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.
您可能希望:
- 在调用
每个()
$ b $之前定义一个变量b - 在每个循环中为其分配一个值
- 在
getColorOptionSelect
$结尾处返回该变量b $ b
- define a variable before you call
each()
- assign a value to it inside the each loop
- return that variable at the end of
getColorOptionSelect
这篇关于Jquery .each() - 返回值未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!