在对象内调用时,函数不起作用

时间:2011-06-09 18:07:20

标签: javascript jquery ajax

我有以下代码:

// auto_suggest.js
function AutoSuggest(textboxElem, resultElem, url) {
    this.textboxElem = textboxElem;
    this.resultElem  = resultElem;
    this.url         = url;
    this.registerEvent();
}

AutoSuggest.prototype = {
    registerEvent: function() {
        this.textboxElem.onkeyup = this.getSuggestions;
    },
    getSuggestions: function() {
        // This doesn't work either: this.loadResponse("some data");
        $.get(this.url, { text: this.textboxElem.value }, this.loadResponse);
    },
    loadResponse: function(data) {
        // Not called
        this.resultElem.innerHTML = data;
    }
};

// suggest.html
<script src="jquery-1.6.1.js" type="text/javascript"></script>
<script src="auto_suggest.js" type="text/javascript"></script>

<script>
$(function() {
    var suggest = new AutoSuggest(document.getElementById("suggest"), 
                                  document.getElementById("result"), 
                                  "result.txt");
        // This DOES work: suggest.loadResponse("123");
});
</script>

<input type="text" id="suggest" /><br>
<div id="result"></div>

函数loadResponse拒绝从对象内部调用,但是从外部调用它很好。可能是什么问题?

2 个答案:

答案 0 :(得分:3)

默认情况下,AJAX回调(AutoSuggest.loadResponse)将jqXHR对象作为其上下文(this值)传递。您需要将context选项传递给$.ajax来覆盖此设置。将$.get函数替换为:

$.ajax({
    url: this.url,
    type: 'GET',
    data: { text: this.textboxElem.value },
    success: this.loadResponse,
    context: this
});

这使得jQuery将this设置为正确的值。

答案 1 :(得分:0)

代码

this.textboxElem.onkeyup = this.getSuggestions;

应该是

var t = this;
this.textboxElem.onkeyup = function() {
    t.getSuggestions();
}