Jquery .each() -返回值未定义
Jquery .each() - return value undefined
为什么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
}
});
相关文章:
- "日期“;AJAX请求返回的类型值未定义
- 为什么在循环中返回时函数返回值未定义
- 使用deferred.resolve(Value)返回给my.then()的值未定义
- 来自 ajax 中 JSON 响应的值返回为未定义
- 为什么 JavaScript 函数的返回值未定义
- 函数返回值未定义
- 返回的 Ajax 响应指出其属性值未定义
- 函数的第一个返回值未定义
- Get-day文本函数返回了未定义的值
- 调用javascript函数时,值在控制台中返回为未定义
- 函数未返回值-未定义
- Node.js:数据库查询后返回值未定义
- 为什么我的返回值未定义(JavaScript)
- Bluebird承诺:any()集合返回值未定义
- Javascript函数返回值未定义
- 使用电子邮件和密码创建用户,返回值未定义的非空用户
- 模态对话框返回值未定义-将结果发送到父窗口
- jQuery AJAX.返回值未定义
- Jquery .each() -返回值未定义
- 返回值未定义