简体   繁体   English

谷歌标签管理器中的自定义 Javascript 返回未定义

[英]Custom Javascript in google tag manager return undefined

in my footer i have a div section structured as follow:在我的页脚中,我有一个结构如下的 div 部分:

<div id="text_icl-7" class="widget widget_text_icl">        
<div class="textwidget">
<p style="text align:justify;">
<img src="image.jpg" alt="YC logo">
Some text
</p>
</div>
</div>

I want capture into a variable the text value, so i write this in gtm:我想将文本值捕获到一个变量中,所以我在 gtm 中写了这个:

function () {
var desc = document.getElementById("text_icl-7").childNodes[1];
var p = desc.childNodes[1].childNodes[2];
return p;
}

The problem is that, debugging the page, the variable's value is undefined.问题是,调试页面时,变量的值是未定义的。 I try the script in another custom page and it works, i write the script in this way:我在另一个自定义页面中尝试脚本并且它有效,我以这种方式编写脚本:

(function(d) {
var desc = document.getElementById("text_icl-7").childNodes[1];
var p = desc.childNodes[1].childNodes[2];
console.log(p)


})(document)

In console i get the text but not in tag manager, why??在控制台中我得到文本但在标签管理器中没有,为什么? thanks谢谢

I can't debug why you're getting undefined values, but I suspect a custom JavaScript variable is not what you need in this instance.我无法调试为什么您会得到未定义的值,但我怀疑自定义 JavaScript 变量不是您在此实例中所需要的。

You can return the text contained within a DOM element by using a Google Tag Manager 'DOM Variable'.您可以使用 Google 标签管理器“DOM 变量”返回包含在 DOM 元素中的文本。 Configure your variable to use a CSS selector that selects elements that match #text_icl-7 > p .将变量配置为使用 CSS 选择器来选择与#text_icl-7 > p匹配的元素。 Leaving the 'attribute' field empty will return the text contained with the element by default.默认情况下,将“属性”字段留空将返回元素中包含的文本。

DOM 变量

i was helped by gtm forum.我得到了 gtm 论坛的帮助。 The corret script is:正确的脚本是:

function() {
  var el = document.querySelector('#text_icl-7');
  return el && (el.textContent || el.innerText);
}

Now it works, maybe the solution of a dom variable also would works, thanks现在它有效了,也许 dom 变量的解决方案也有效,谢谢

Sorry to respond to late this but here is my solution, you need define the variable at the beginning of the script and return it at the end.抱歉回复晚了,但这是我的解决方案,您需要在脚本开头定义变量并在结尾返回它。 Example below.下面举例。

This NOT works:这不起作用:

function(){
  document.querySelectorAll('.some-class').forEach(function(item){
    var displayStyle = item.style.display;

    if (displayStyle === 'block'){
      return item.getAttribute('id');
    }
  })
}

But this works:但这有效:

function(){
  var result = '';
  document.querySelectorAll('.some-class').forEach(function(item){
    var displayStyle = item.style.display;

    if (displayStyle === 'block'){
      result = item.getAttribute('id');
    }
  })
  return result;
}

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

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