我在我的网页底部有一张地图,当用户向下滚动到地图时,我希望google标记下降和具体的时间。我已经让它起作用了。问题是它一直在调用函数,我怎么才能只调用一次呢?
这是我现在的JS代码,我试图找出这个bug:
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300 &&
$(window).scrollTop() <= $(document).height() - $(window).height() - 200
) {
var dropOnlyOnce = (function(){
dropped = false;
if (dropped == false) {
dropMarker(); // this is the function I'm calling
}
dropped = true;
})();
}
});我怎么才能让它工作,或者我怎么才能只调用一次dropMarker函数?
发布于 2014-10-21 09:07:13
一旦调用了函数,您就可以删除侦听器:
$(window).on('scroll', function(e) {
if( ...window at scrollTop ) {
$(window).off('scroll')
.... Drop your pin
}
})Esteban Felix的评论提出了一个很好的观点。这将删除所有滚动处理程序。如果这对你不起作用,你可以将函数移到处理程序之外,并且只删除它:
var dropPinOnce = function() {
if( ... window at correct scrollTop ) {
... Drop pin here ...
$(window).off('scroll', dropPinOnce)
}
$(window).on('scroll', dropPinOnce)发布于 2014-10-21 09:22:03
试一试
var callbacks = $.Callbacks("once")
, dropMarker = function() {
// do stuff
};
callbacks.add(dropMarker);
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300 &&
$(window).scrollTop() <= $(document).height() - $(window).height() - 200
) {
var dropOnlyOnce = (function(){
dropped = false;
if (dropped == false) {
callbacks.fire() // call `dropMarker` "once"
}
dropped = true;
})();
}
});请参阅"Possible Flags“->中的jQuery.Callbacks "once”
var callbacks = $.Callbacks("once")
, dropMarker = function() {
console.log(123)
};
callbacks.add(dropMarker);
$(window).scroll(function () {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 300 &&
$(window).scrollTop() <= $(document).height() - $(window).height() - 200
) {
var dropOnlyOnce = (function(){
dropped = false;
if (dropped == false) {
// dropMarker(); // this is the function I'm calling
callbacks.fire()
}
dropped = true;
})();
}
});div {
height : 500px;
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>abc</div>
发布于 2014-10-21 09:38:40
如果你只是在你的条件满足后解除绑定,那么你的函数实际上只会被调用一次。
$(window).scroll(function callOnceOnScroll() {
var $window = $(window),
$document = $(document);
if ($window.scrollTop() >= $document.height() - $window.height() - 300 &&
$window.scrollTop() <= $document.height() - $window.height() - 200) {
$window.off('scroll', callOnceOnScroll);
dropMarker(); // this is the function I'm calling
}
});https://stackoverflow.com/questions/26477322
复制相似问题