我有以下javascript类,并且由于某种原因,当我完成加载记录时,当前属性未设置为-1(或者我无法从类的实例正确访问属性) 。 我是javascript的新手,所以任何帮助都会受到赞赏。
var MyLib = function () {
this.current = 0;
MyLib.prototype.loadMore = function (id, loadingDivId, url) {
if (this.current > -1) {
this.current++;
$(loadingDivId).html("<h3>Loading more records please wait...</h3>");
$.get(url + this.current, function (data) {
if (data != '') {
$(id).append(data);
$(loadingDivId).empty();
} else {
this.current = -1; // seems like this isn't being set
$(loadingDivId).html("<h3><i>-- No more results -- </i></h3>");
}
});
}
}
};
以下是我如何称呼它
<script type="text/javascript">
$(function () {
var lib = new MyLib();
$('#loadMore').click(function () {
if (lib.current > -1) {
lib.loadMore("#results", "#loading", '/home/search/');
if (lib.current == -1) {
// Having problems getting into this portion
$("#loadMore").hide();
}
}
return false;
});
});
</script>
答案 0 :(得分:1)
原型走出功能声明
var MyLib = function () {
this.current = 0;
};
MyLib.prototype.loadMore = function (id, loadingDivId, url) {
if (this.current > -1) {
this.current++;
$(loadingDivId).html("<h3>Loading more records please wait...</h3>");
$.get(url + this.current, function (data) {
if (data != '') {
$(id).append(data);
$(loadingDivId).empty();
} else {
this.current = -1; // seems like this isn't being set
$(loadingDivId).html("<h3><i>-- No more results -- </i></h3>");
}
});
}
}
答案 1 :(得分:1)
虽然@Gnostus关于原型放置是正确的,但是你有一个问题,因为你正在发出异步请求,但是在发送请求后却试图立即使用响应。
换句话说, loadMore()
次调用之后的代码在收到回复之前运行。
更改原型以接受要在回调中使用的function
。
// accept a function to call upon success ---------------v
MyLib.prototype.loadMore = function (id, loadingDivId, url, fn) {
if (this.current > -1) {
this.current++;
$(loadingDivId).html("<h3>Loading more records please wait...</h3>");
$.get(url + this.current, function (data) {
if (data != '') {
$(id).append(data);
$(loadingDivId).empty();
} else {
this.current = -1;
// ------------v------call the function
fn();
$(loadingDivId).html("<h3><i>-- No more results -- </i></h3>");
}
});
}
}
然后传递依赖于响应的功能。
$('#loadMore').click(function () {
if (lib.current > -1) {
// pass in your function -----------------------------v
lib.loadMore("#results", "#loading", '/home/search/', function() {
// This if() statement could be removed, since it will
// always be "true" in the callback.
// Just do the $("#loadMore").hide();
if (lib.current == -1) {
$("#loadMore").hide();
}
});
}
return false;
});
或者,如果这是标准功能,您可以将该功能添加到prototype
的{{1}},并让它接受相关参数。然后,您的MyLib
只需从loadMore
调用即可。