如何使用jquery在调用函数内传递函数的变量?

时间:2012-11-09 04:43:27

标签: javascript jquery scope

使用以下代码我无法在调用函数更改中获取this.select的值...见下文

function getSelection(selectionType) {
    this.select = selectionType;
    alert(this.select); // works
    this.getFile = function() {
        $(".file").change(function() {
            alert($(this).attr("id")); // works
            alert(this.select); // says undefined
            if ($(this).attr("id") == this.select) {
                alert("test"); // no display
            }
        });
    };
}​

1 个答案:

答案 0 :(得分:4)

缓存this

function getSelection(selectionType) {
    var that = this; // <========================
    this.select = selectionType;
    alert(this.select);

    this.getFile = function() {
        $(".file").change(function() {
            alert($(this).attr("id"));
            alert(that.select);
            if ($(this).attr("id") == that.select) {
                alert("test");
            }
        });
    }
}​