简体   繁体   English

谷歌标签管理器没有引用 jQuery? “$ 不是函数”

[英]Google Tag Manager not referencing jQuery? "$ is not a function"

Going to start off by saying I have very limited experience with JS and jQuery, so I'm flailing around a bit here.首先要说我对 JS 和 jQuery 的经验非常有限,所以我在这里有点犹豫。

I've got a GTM custom HTML tag that uses jQuery to grab the text from label/legend elements associated with a specific error message class, and push each one to the dataLayer for event handling:我有一个 GTM 自定义 HTML 标签,它使用 jQuery 从与特定错误消息 class 关联的标签/图例元素中获取文本,并将每个标签推送到 dataLayer 以进行事件处理:

 <script type="text/javascript" id="error-push"> jQuery( document ).ready(function() { var errMsgs = document.getElementsByClassName("error_message"); for (i = 0; i < errMsgs.length; i++) { var assocLabel = $(errMsgs[i]).closest(".field_error").find(".field_label").text(); if(assocLabel) { dataLayer.push({'field-error': assocLabel}); } } }); </script>

I can get the function to run no problem when tested directly in my browser console.在我的浏览器控制台中直接测试时,我可以让 function 运行没有问题。 But when I run it via GTM, I get an Uncaught TypeError:但是当我通过 GTM 运行它时,我得到了一个 Uncaught TypeError:

Uncaught TypeError: $ is not a function
    <anonymous> https://example.com/form/?gtm_debug=1661509869380 line 348 > injectedScript:1
    jQuery 2
        e
        t
register:1:218

At first I thought that GTM was just firing the script before jQuery was loaded, so I included an extra line at the top of the script in GTM to check for it:起初我以为 GTM 只是在加载 jQuery 之前触发了脚本,所以我在 GTM 的脚本顶部添加了一个额外的行来检查它:

<script type="text/javascript" id="error-push">
  typeof window.jQuery !== 'undefined' ? console.log(window.jQuery.fn.jquery) : 'jQuery not found!'
  jQuery( document ).ready(function() { ...

...And the console is returning "3.6.0", indicating that jQuery is loaded when the function runs. ...并且控制台返回“3.6.0”,表明 function 运行加载了 jQuery。 So where is the TypeError coming from?那么 TypeError 是从哪里来的呢?

My personal practice for Google Tag Manger is not using jQuery within it.我个人对 Google Tag Manger 的做法是没有在其中使用 jQuery。

Because it will have so many error that not sure why it comes up.因为它会有很多错误,不知道为什么会出现。

In your case:在你的情况下:

I suggest you use the trigger Dom Ready .我建议你使用触发器Dom Ready From what I know it is quite the same when you want to fire something as jQuery( document ).ready(function() {}据我所知,当你想触发jQuery( document ).ready(function() {}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM