Jquery,从函数访问变量
我有这段代码
function getSelectData(id) {
jQuery(id).change(function () {
var value='';
jQuery(id+" option:selected").each(function () {
value =jQuery(this).val() ;
});
console.log(value);
});
return value;
}
var d = getSelectData("#sort_post_date");
console.log(d);
如何访问变量“value”,我尝试了不同的方法,但没有任何结果,console.log(value); 在哪里,值退出,但外面什么都没有,谢谢您的帮助!
I have this code
function getSelectData(id) {
jQuery(id).change(function () {
var value='';
jQuery(id+" option:selected").each(function () {
value =jQuery(this).val() ;
});
console.log(value);
});
return value;
}
var d = getSelectData("#sort_post_date");
console.log(d);
How i can access variable "value" , i tried different methods , but nothing , where is console.log(value); , value exit , but outside nothing , Thank You for Helping !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不需要将值移到函数之外,以便将其绑定到闭包。像这样:
这是显示它工作原理的小提琴: http://jsfiddle.net/ZvuMh/
You need ot move value outside of the function so it is bound to the closure. Like this:
Here is the fiddle to show it works : http://jsfiddle.net/ZvuMh/
这是一个经典的封闭式问题。以下是一些最相似的
Javascript 循环内的事件处理程序- 需要闭包?
已创建 JavaScript 计时器或间隔在循环中使用闭包
循环内的Javascript闭包 - 简单的实际示例
最重要的是,
value
变量对于您正在创建的事件处理程序来说不是本地的。因此,您创建的所有处理程序都将具有外部函数结束时的值。在这种情况下,它仍然是空白的。This is a classic closure question. Here are some of the most similar ones
Event handlers inside a Javascript loop - need a closure?
javascript timer or intervals created in loop using closure
Javascript closure inside loops - simple practical example
Bottom line, the
value
variable is not local to the event handlers you're creating. So all of the handlers you create are going to have the value thatvalue
had when the outer function ended. In this case, it is still blank.您无法在声明它的函数之外访问您的值变量。这称为变量范围。在此处阅读变量作用域
如果您希望能够访问变量,您需要位于一个至少与声明它的范围一样通用的范围内。
所以在这种情况下:
You cannot access your value variable outside of the function it was declared in. This is called the variable scope. Read up on variable scope here
If you want to be able to access a variable, you need to be in a scope that is at least as general as the one it was declared in.
So in this case :
尝试在全局范围内定义值变量:
这里返回“值”也是没有意义的,因为它是在事件处理程序中设置的......那里不会有任何东西(或者只是一个旧值)返回点。
Try definining the value variable in the global scope:
There's also no point in returning 'value' here, since it's being set in an event handler...there won't be anything in there (or, just an old value) at the point of return.