我有以下代码:
// 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
拒绝从对象内部调用,但是从外部调用它很好。可能是什么问题?
答案 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();
}