【问题标题】:Converting arrow function to regular function - For use in Google Tag Manager将箭头函数转换为常规函数 - 用于 Google 跟踪代码管理器
【发布时间】:2021-05-05 11:36:14
【问题描述】:

我想在 GTM 中使用该脚本:

<script>
var isOverIFrame = false
var iframes = window.document.querySelectorAll('iframe');
function trackIframeClicks(frames){
  window.addEventListener('blur',function(e) {
    frames.forEach(function (frame, index) {
      if (frame.mouseOver) {
        window.dataLayer.push({
          'event': 'ifameClick',
          'frameSource': frame.src
        });
        // console.log(frame.src);
      }
    })
  });
}
function setListeners (frames) {
  frames.forEach(function(frame) {
    frame.mouseOver = false
    frame.addEventListener('mouseenter', () =>{
      frame.mouseOver = true
      // console.log('mouse in iframe')
    });
    frame.addEventListener('mouseleave', () =>{
      frame.mouseOver = false
      // console.log('mouse out of iframe')
    });
  })
}
setListeners(iframes);
trackIframeClicks(iframes);
</script>

尝试发布时出现以下错误:

第 20 行和第 24 行错误,字符 42:此语言功能仅支持 ECMASCRIPT_2015 或更高模式:箭头函数。

有人可以帮忙重写这个函数,让它在没有箭头函数的情况下工作吗?

非常感谢。

【问题讨论】:

  • 我推荐这个页面,你可以自己看看es6是怎么转成es5的babeljs.io
  • @GrzegorzT。谢谢你。会检查!

标签: javascript google-tag-manager arrow-functions


【解决方案1】:
    function setListeners (frames) {
  frames.forEach(function(frame) {
    frame.mouseOver = false
    frame.addEventListener('mouseenter',function enter (){
      frame.mouseOver = true
      // console.log('mouse in iframe')
    });
    frame.addEventListener('mouseleave',function leave () {
      frame.mouseOver = false
      // console.log('mouse out of iframe')
    });
  })
}

【讨论】:

  • 没有太多解释,希望这是一个很好的开眼界。 :) EC5!
  • 哦,你也可以设置 /*jshint esversion: 8 */ 为你的项目顶部的错误函数和“使用严格”;在您的上层范围函数中。如果要寻求更高的支持,但 EC5 太棒了。
  • 谢谢@blanknamefornow - 工作!
  • 没问题,希望你看看我在那里做了什么。快速切换! :D
【解决方案2】:
// An arrow function
() => {
  ...
}
// is shorthand syntactic sugar for
(function () { 
  ...
}).bind(this)

但由于您不需要绑定到 this,您可以放弃它并使用普通函数。

function () {
   ...
}

【讨论】:

  • 感谢您的解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-06
  • 1970-01-01
  • 2019-07-10
  • 2017-12-20
  • 2022-01-13
  • 2018-03-11
  • 2020-02-20
相关资源
最近更新 更多