Javascript - get image alt text of clicked link fo

2019-06-04 19:09发布

问题:

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.