Jquery , access variable from function
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 = getSelectDa开发者_StackOverflowta("#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 !
You need ot move value outside of the function so it is bound to the closure. Like this:
function getSelectData(id) {
var value='';
// set value to be the current selected value
value = jQuery(id+" option:selected").val();
// change value whenever the box changes
jQuery(id).change(function () {
value = jQuery(id+" option:selected").val();
console.log("I see a change! -> "+value);
});
console.log(value);
return value;
}
var d = getSelectData("#sort_post_date");
console.log(d);
Here is the fiddle to show it works : http://jsfiddle.net/ZvuMh/
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 that value
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 :
function getSelectData(id){
var value='';
jQuery(id).change(function () {
jQuery(id+" option:selected").each(function () {
value =jQuery(this).val() ;
});
console.log(value);
});
return value;
}
var d=getSelectData("#sort_post_date");
console.log(d);
Try definining the value variable in the global scope:
var value='';
function getSelectData(id) {
jQuery(id).change(function () {
value='';
jQuery(id+" option:selected").each(function () {
value =jQuery(this).val() ;
});
console.log(value);
});
return value;
}
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.
精彩评论