我有这个代码
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);在哪里? ,值退出,但外面什么都没有,谢谢您的帮助!
最佳答案
您需要将值移到函数之外,以便将其绑定(bind)到闭包。像这样:
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);
这是显示其工作原理的 fiddle :http://jsfiddle.net/ZvuMh/
关于Jquery,从函数访问变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4100524/