Javascript jquery函数返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6861039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery function return value
提问by Stephen S.
I've created a function to iterate through a UL/LI. This works perfectly, my problem is returning the value to another variable. Is this even possible? What's the best method for this? Thanks!
我创建了一个函数来遍历 UL/LI。这很有效,我的问题是将值返回给另一个变量。这甚至可能吗?最好的方法是什么?谢谢!
function getMachine(color, qty) {
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
return thisArray[3];
}
});
}
var retval = getMachine(color, qty);
回答by Alex Turpin
I'm not entirely sure of the general purpose of the function, but you could always do this:
我不完全确定该函数的一般用途,但您始终可以这样做:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
var retval = getMachine(color, qty);
回答by Milimetric
The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:
您拥有的 return 语句卡在内部函数中,因此它不会从外部函数返回。你只需要多一点代码:
function getMachine(color, qty) {
var returnValue = null;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
returnValue = thisArray[3];
return false; // this breaks out of the each
}
});
return returnValue;
}
var retval = getMachine(color, qty);