[英]How to prevent jQuery function from being initialized more than once (Drupal behaviours involved)?
我的目標:使用戶能夠加載模板(包含預設的jquery,html和css),以允許他們單擊五個點之一以觸發圖像上的動畫。
我的問題:當我在頁面上加載多個這些模板時,我的動畫值(在這種情況下為margin-left)應用的次數是頁面上此模板實例的兩倍。 如果我的模板加載了兩次,則左邊距設置為一個值,跳至正確的值,然后返回,最后設置為正確的值。 這意味着,如果我要向該頁面添加10個實例,則獲取該最后一個值所需的時間將是原來的20倍。
在測試之前,我認為我的代碼還可以,因為上下文和.once()
函數,我相信它只會觸發一次。
所有的html和CSS都按預期運行,只是jQuery是一個問題。
我的代碼:
(function ($) {
Drupal.behaviors.click_the_dots = {
attach: function (context, settings) {
$('.wrapper_class', context).once('click_the_dots', function () {
// Prevent other buttons from being clickable until the
// previous animation is complete.
var animationDone = false;
function clickDots(dotNum) {
$('.dot_class_num_' + dotNum).click(function () {
// Setup context, to keep animations to the container in which the dots exist.
var findElem = $(this).parent().parent().parent().find('.inner_wrapper');
// Prevent other buttons from being clickable until the
// previous animation is complete.
if (animationDone === false) {
animationDone = true;
// Find the visible image.
var animatingImage = findElem.find('.dot_class_num_active');
// Find the image that will be animating in.
var thisImageAnim = findElem.find('.dot_num_img_src_' + dotNum);
if (animatingImage.is(thisImageAnim)) {
// Can't click on the same dot again, until another dot is clicked.
animationDone = false;
return;
} else {
// Animate out the already visible image.
// Remove the visible image class as it's going to be hidden.
findElem.find('.dot_class_num_active').removeClass('dot_class_num_active');
// Animate it to hide to the left.
animatingImage.animate({
marginLeft: '-10%',
opacity: 0
}, 280, 'easeInOutQuad');
// Animate in the image associated with the dot click
// Set the image css to be further right in order to animate to left at 0.
thisImageAnim.css('margin-left', '10%').delay(200).animate({
marginLeft: '0',
opacity: 1
}, 300, 'easeInOutQuad', function () {
// Set the now visible image to the visible image.
thisImageAnim.addClass('dot_class_num_active');
}).promise().done(function () {
// Now allow the other dots to be clicked.
animationDone = false;
});
}
}
});
}
// For each of the five dots.
for (i = 1; i <= 5; i++) {
clickDots(i);
}
});}};})(jQuery);
我想根據需要添加此jQuery的盡可能多的實例,但僅使函數循環一次。 我不確定如何檢查是否已經完成,或者如何確保一旦完成至少一次就不會再次發生。
:)
我弄清楚我的問題是-我將行為附加到我的內容的包裝類,即$('.wrapper_class', context).once...
這意味着它將行為附加到了該類的每個實例,其中可能有很多。
我所做的就是將行為附加到較高的父元素,我知道只有一個實例。 它僅附加一次,代碼運行完美。
感謝上面的評論員幫助我意識到了我的問題!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.