使用 Google 跟踪代码管理器将动态键值对推送到数据层时遇到问题
我正在尝试使用 Google 跟踪代码管理器收集并触发表单字段作为 dataLayer 变量:
<script>
var fields = [];
var fields = document.querySelectorAll("input");
var x = fields.forEach(function(field) {
var obj = {};
var a = field.getAttribute("name");
var b = field.value;
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
obj[a] = b
});
});
</script>
我的意图是,当触发时,:
- 收集字段中的所有表单值
- 迭代项目数组并获取字段的名称和值
- 触发名称和值作为键值
- 对返回以迭代下一项。
但是,我收到错误:
第 12 行第 10 字符出错:解析错误。预计为“}”
无论我做出什么改变,我似乎都无法正确排除故障。
I'm trying to collect and fire form fields as dataLayer variables using Google Tag Manager:
<script>
var fields = [];
var fields = document.querySelectorAll("input");
var x = fields.forEach(function(field) {
var obj = {};
var a = field.getAttribute("name");
var b = field.value;
window.dataLayer = window.dataLayer || [];
window.dataLayer.push({
obj[a] = b
});
});
</script>
My intention is, when triggered, to:
- Collect all of the form values in fields
- Iterate over the array of items and get the field's name and value
- Fire the name and value as a key-value pair
- Return to iterate over the next item.
However, I'm receiving the error:
Error at line 12, character 10: Parse error. '}' expected
And no matter what changes I make, I can't seem to properly trouble shoot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
push
函数中不能有=
。您可以稍微更改您的代码。在推送之前先进行赋值,如 obj[a] = b,然后在每次迭代时将对象推送到 dataLayer 中。
下面的工作代码逻辑
You can't have a
=
in thepush
function. You can change your code slightly.Do the assignment before pushing like
obj[a] = b
, and then push the object in dataLayer at each iteration.Working code logic below