Jquery,从函数访问变量

mIR*_*IRU 1 variables jquery closures

我有这个代码

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);
Run Code Online (Sandbox Code Playgroud)

我如何访问变量"值",我尝试了不同的方法,但没有,哪里是console.log(值); ,价值退出,但不在外面,谢谢你的帮助!

Hog*_*gan 9

你需要在函数之外移动值,以便绑定到闭包.像这样:

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);
Run Code Online (Sandbox Code Playgroud)

这是表明它有效的小提琴:http://jsfiddle.net/ZvuMh/