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 に答える