0

使用以下代码我无法在调用函数更改中获取 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
            }
        });
    };
}​
4

1 回答 1

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");
            }
        });
    }
}​
于 2012-11-09T04:47:08.823 回答