Javascript - 获取Google跟踪代码管理器点击链接的图片替代文字 [英] Javascript - get image alt text of clicked link for Google Tag Manager
问题描述
我想在用户点击它时使用下面的Javascript捕获图像的alt属性,但我可以获得的结果始终为null。我想提取Youtubealt属性。
I want to use the Javascript below capturing the alt attribute of an image when user click on it, but the result I can get is always null. I want to extract the "Youtube" alt attribute.
<a href="http://www.youtube.com/" title="Youtube" target="_blank">
<img src="/example" class="example" alt="Youtube">
</a>
function() {
var elem = {{element}},
attr = "alt", // change to corresponding attributes
result = (elem.getAttribute && elem.getAttribute(attr)) || null;
if( !result ) {
var attrs = elem.attributes,
l = attrs.length;
for(var i = 0; i < l; i++) {
if(attrs[i].nodeName === attr)
result = attrs[i].nodeValue;
}
}
return result;
}
推荐答案
我假设JS你上面发布的代码是GTM JS宏吗?我不确定你是否有点击监听器或链接点击监听器,但如果它是第二个,则它必然不起作用,因为alt是图像的属性而不是链接。如果你有一个链接点击监听器,这个JS GTM宏可能只是工作:
I'm assuming the JS code you posted above is a GTM JS macro? I'm not sure if you have a click listener or a link click listener, but if it's the second, it's bound not to work because alt is an attribute of the image and not the link. In case you have a link click listener, this JS GTM macro might just work:
function(){
var self = {{element}};
if (typeof self.children === 'undefined' || self.children.lenght == 0 || typeof self.children[0].alt === 'undefined')
{
return '';
}
return self.children[0].alt;
}
你也可以调整你自己的代码来获取孩子的属性 img
。
You could also adjust your own code to take the attribute from the child img
.
这篇关于Javascript - 获取Google跟踪代码管理器点击链接的图片替代文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!