我正在制作一个进度条,并希望它在视口(viewport)中时播放。我得到了这个工作,但代码现在每次都会执行,我只需要它运行一次。因为它现在创建了多个进度条。 ;-) 下面的代码在 Joomla 扩展中使用。
(function ($) {
$(document).ready(function() {
// Function that checks if it is in view.
$("<?php echo '#progress' . $module->id ?>").waypoint(function() {
// Function that makes sure it only runs once.
// -----------I need to use .one() here but how?
// The location of the progressbar code for now lets put a alert in.
alert("run only once");
}, {
offset: '50%'
});
});
})(jQuery);
我一直在阅读有关 .one() 函数以及如何在此处使用它的信息。但我尝试了使用 click
和 ready
的示例,虽然 click 不是我想要的,但 Ready 应该可以解决问题,但没有任何效果。
最佳答案
您可以使用 $.Callbacks()
并以 "once"
作为参数。
(function ($) {
$(document).ready(function() {
function runOnce() {
// Function that makes sure it only runs once.
// -----------I need to use .one() here but how?
// The location of the progressbar code for now lets put a alert in.
alert("run only once");
}
var callbacks = $.Callbacks("once");
callbacks.add(runOnce);
// Function that checks if it is in view.
$("<?php echo '#progress' . $module->id ?>").waypoint(function() {
callbacks.fire(runOnce);
}, {
offset: '50%'
});
});
})(jQuery);
关于javascript - jquery 在视口(viewport)中运行一次 .one(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39709512/