函数不返回变量
我有一个函数,它接受一个参数(键)来从 cookie 中检索它的值。我在需要特定信息的任何地方调用该函数。除非一切都返回为未定义。
//before $(document).ready();
var keyval = ""; //VARIABLE FOR PASSING COOKIE VALUE
var getCookieVal =function(c_name){
var cleanCookie = document.cookie.substr(0, document.cookie.indexOf("; __utma="));//REMOVES EXTRA INFORMATION
var cookieArr = cleanCookie.split(";");//MAKES AN ARRAY OF EACH PAIR
$.each(cookieArr, function(index, val){
var valArr = val.split("=");//SPLITS THE KEY VALUE PAIR INTO AN ARRAY
var key = valArr[0];
keyval = valArr[1];
if (key == c_name){
alert(keyval);//ALERTS CORRECT ANSWER
return keyval;
}
});
console.log(keyval);//RETURNS UNDEFINED
}
//IN ANOTHER FILE I CALL THE FUNCTION:
$(document).ready(function(){
getCookieVal("username");
alert(keyval);//RETURNS UNDEFINED
});
有人知道我做错了什么或者我如何获得这个值?
I have a function that takes a parameter(key) to retrieve it's value from a cookie. I call that function anywhere that I need a specific bit of information. except everything comes back as Undefined.
//before $(document).ready();
var keyval = ""; //VARIABLE FOR PASSING COOKIE VALUE
var getCookieVal =function(c_name){
var cleanCookie = document.cookie.substr(0, document.cookie.indexOf("; __utma="));//REMOVES EXTRA INFORMATION
var cookieArr = cleanCookie.split(";");//MAKES AN ARRAY OF EACH PAIR
$.each(cookieArr, function(index, val){
var valArr = val.split("=");//SPLITS THE KEY VALUE PAIR INTO AN ARRAY
var key = valArr[0];
keyval = valArr[1];
if (key == c_name){
alert(keyval);//ALERTS CORRECT ANSWER
return keyval;
}
});
console.log(keyval);//RETURNS UNDEFINED
}
//IN ANOTHER FILE I CALL THE FUNCTION:
$(document).ready(function(){
getCookieVal("username");
alert(keyval);//RETURNS UNDEFINED
});
Anyone know what I did wrong or how I can get that value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
开始吧:
因此,您在 if 分支内
返回 false
(一旦找到所需的值)即可跳出$.each
循环。然后,您只需从getCookieVal
函数返回值
即可。请注意,这里不需要定义全局
keyval
变量。Here you go:
So you
return false
inside the if-branch (once you find the desired value) to break out of the$.each
loop. Then, you justreturn value
from thegetCookieVal
function.Note that there is no need to define a global
keyval
variable here.此行:
...从您传递给
$.each
的匿名函数返回,而不是从您的getCookieVal
函数返回。This line:
...returns from the anonymous function you passed to
$.each
, not from yourgetCookieVal
function.您需要
返回 false
才能跳出循环。否则,循环将继续,keyval
被覆盖。您正在返回keyval
,这不会破坏循环。将其更改为false
就可以了。You need to
return false
to break out of your loop. Otherwise, the loop continues andkeyval
is overwritten. You are returningkeyval
, which will not break the loop. Change that tofalse
and you should be good.您的代码可以简化为这样(假设 getCookieVal 的调用者是可信的)
Your code could be reduced to this (assuming that caller of getCookieVal is trusted)