Google 标签管理器 - 获取 javascript 变量中元素的父元素

Google Tag manager - Get parent of element in a javascript variable

在自定义javascript变量中,如何获取被点击元素的父元素?

<div>
    <h2>Lorem Ipsum</h2>
    <a href="#"></a>
</div>

例如,我想在单击 <a> 时获取 <H2> 的内容,以便在单击 <a> 时记录 Lorem Ipsum。

有了 Jquery,你可以做这样的事情

$('a').click(function(){
 var h2Content = $(this).siblings('h2').text();
 console.log(h2Content);
});

请注意,这段代码会在所有标签上放置一个点击事件处理程序。

似乎 Click Element 变量在这里工作得很好。很奇怪,我在 '' 中使用了它,这使得它 return 只有 url。但是你可以像这样使用它

function(){
    var title = jQuery({{Click Element}}).parent().find('h2').html();

    return title;
}

我知道这是一个较旧的问题,但在我自己搜索这个确切问题时,我发现 this really helpful link 有一个解决方案。

您可以添加自定义变量。为此,在 Google 标签管理器中转到 Variables,在 User-Defined Variables 下单击 New。 Select Variable Type of Custom JavaScript,将其命名为 Find Closest 并输入以下代码:

function() {
  return function(target, selector) {
    while (!target.matches(selector) && !target.matches('body')) {
      target = target.parentElement;
    }
    return target.matches(selector) ? target : undefined;
  }
}

为您的具体情况添加另一个 JavaScript 变量。类似于:

function() {
    var parentElement = {{Find Closest}}({{Click Element}}, 'div'),
        childElement = typeof parentElement !== 'undefined' ? parentElement.querySelector('h2') : undefined;
    return typeof childElement !== 'undefined' ? childElement.innerText : undefined;
}

注意:您可以为 matches 添加一个 polyfill 用于旧版浏览器。