Javascript - get image alt text of clicked link for Google Tag Manager

≯℡__Kan透↙ 提交于 2019-12-23 03:15:11

问题


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;
}

回答1:


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;
}

You could also adjust your own code to take the attribute from the child img.



来源:https://stackoverflow.com/questions/27528991/javascript-get-image-alt-text-of-clicked-link-for-google-tag-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!