[英]Javascript DataLayer Fetch from
I'd like to pull data from my HTML code into my dataLayer (Google Tag Manager). 我想将数据从HTML代码中提取到dataLayer(Google跟踪代码管理器)中。
The html code is something like this: html代码是这样的:
<body class="portal sessions" data-place="hun">...</body>
And the Javascript Code is something like this: Javascript代码是这样的:
<script type="text/javascript">
var lang_log = document.getElementsByClassName("portal");
dataLayer.push({
"language_login":lang_log
})
</script>
What I'd try is to give to the lang_log variable the "hun" value and I'd try: 我想给lang_log变量赋“ hun”值,然后尝试:
<script type="text/javascript">
var lang_log = document.getElementsByClassName("portal")['data-place'];
dataLayer.push({
"language_login":lang_log
})
</script>
But it's not working. 但这不起作用。 Any ideas?
有任何想法吗?
Any help or advice is apprecaited, Thank you in advance. 如有任何帮助或建议,请先谢谢您。
document.getElementsByClassName("portal")
returns an array-like collection of elements. document.getElementsByClassName("portal")
返回类似数组的元素集合。
You can get the first element of this collection with document.getElementsByClassName("portal")[0]
. 您可以使用
document.getElementsByClassName("portal")[0]
获取此集合的第一个元素。
To access the data attribute , use document.getElementsByClassName("portal")[0].dataset.place
. 要访问数据属性 ,请使用
document.getElementsByClassName("portal")[0].dataset.place
。
var AdataLayer = []; var lang_log = document.getElementsByClassName("portal")[0].dataset.place; AdataLayer.push({ "language_login":lang_log }) console.log(AdataLayer); console.log(AdataLayer[0].language_login);
<body class="portal sessions" id="portal" data-place="hun">...</body>
Found the solution: 找到了解决方案:
the JS should be: JS应该是:
<script type="text/javascript">
var lang_log = document.getElementsByTagName("body")[0].getAttribute("data-locale");
dataLayer.push({
"language_login":lang_log
})
</script>
Still investigating in why the first version did not work! 仍在调查为什么第一个版本不起作用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.