【问题标题】:Reset a run once function重置一次运行功能
【发布时间】:2018-06-21 03:21:45
【问题描述】:

我正在使用 facebook 像素代码来确定用户何时阅读了整篇文章。我有一个无限的博客,所以当用户向下滚动页面时 URL 会发生变化。我目前有一个功能可以在用户到达页面末尾时运行一次,但我需要对其进行修改,以便如果 URL 发生更改,该功能将被重置并可以再次运行。这是我当前的代码。

// determine the position of element
jQuery.fn.isInViewport = function() {
  var elementTop = jQuery(this).offset().top;
  var elementBottom = elementTop + jQuery(this).outerHeight();
  var viewportTop = jQuery(window).scrollTop();
  var viewportBottom = viewportTop + jQuery(window).height();
  return elementBottom > viewportTop && elementTop < viewportBottom;
};

// grab the current URL
var originalURL = window.location.href;

// check to see if element is in viewport
jQuery(window).on('resize scroll', function() {

  var currentURL = '';

  jQuery('.end-of-content-icon').each(function() {

    if (jQuery(this).isInViewport()) {

      currentURL = window.location.href;

      if(originalURL !== currentURL) {

        canOnlyFireOnce();

        originalURL = currentURL;

      }
    }
  });
});

// function to only fire once (courtesy of David Walsh)
function once(fn, context) { 
  var result;

  return function() { 
    if(fn) {
      result = fn.apply(context || this, arguments);
      fn = null;
    }

    return result;
  };
}

// Usage
var canOnlyFireOnce = once(function() {

  fbq('track', 'Lead');

});

【问题讨论】:

  • once() 只触发一次,因为它将自己设置为 null。如果您想多次运行它,则不需要它。尝试将canOnlyFireOnce(); 替换为fbq('track', 'Lead'); 你的条件if(originalURL !== currentURL) 运行它应该足够了。
  • 不幸的是,这不起作用,因为代码在滚动时工作,因此该函数在用户滚动时被多次调用
  • 是的,每次轮子旋转都会触发 10~12 次滚动。但条件是“过滤”。

标签: javascript jquery facebook facebook-pixel


【解决方案1】:

用不同的函数解决它。我通过永久链接并将其添加到数组中。如果数组中不存在永久链接,则将变量“triggerOnce”设置为 true,然后函数运行。

var triggerOnce = true;
var permalinkArray = [];
function callFaceBookPixel(permalink){

  if(permalinkArray.indexOf(permalink) === -1) {
    permalinkArray.push(permalink);
    triggerOnce = true;
  }

  if(triggerOnce){
    triggerOnce = false;
    fbq('track', 'Lead');
  }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 2023-04-01
    • 2018-09-14
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多