我正在尝试从页面上的图块获取h3文本,并将其返回到GTM中的自定义JS变量中。然后,我将创建一个触发器,以在按下按钮时将值保存到GA。
触发按钮操作正常。我只是无法填充变量。
我尝试按照该线程中的说明进行操作:Get element text through GTM Custom JavaScript Variable但是,我在GTM预览调试叠加层中得到“未定义”。
HTML:
<div class="field-item odd" style="display: block;">
<div class="nfsa-filetile file file-video file-video-oembed contextual-links-region view-mode-teaser_tile">
<a href="#" class="nfsa-collection-card-link toc-filter-processed">
<div class="field field-name-field-file-poster-image field-type-image field-label-hidden">
<div class="field-items">
<div class="field-item even">
<picture class="img-responsive">
<img class="img-responsive" src="" alt="some test here. "
title="">
</picture>
</div>
</div>
</div>
<div class="row nfsa-collection-heading">
<div class="col-xs-9">
<h3>This is the heading i want</h3></div>
<div class="col-xs-3 text-right"><i class="nfsa-icon nfsa-color-gray-4 nfsa-icon-video"></i></div>
</div>
<div class="field field-name-field-file-summary field-type-text-long field-label-hidden">
<div class="field-items">
<div class="field-item even">
<p>Some paragraph text here</p>
</div>
</div>
</div>
</a>
</div>
<div class="row nfsa-collection-expand-row">
<div class="nfsa-collection-expand col-xs-8">
<button aria-expanded="false" aria-label="Expand for more information on this item">Expand <i class="glyphicon glyphicon-chevron-up"></i></button>
</div>
</div>
</div>
我已经从链接线程中修改了变量JS。
function() {
return $({{Click Element}}.closest('.field-item')).find('h3').text();
}
我假设使用.field-item会一直遍历到最上面的div,然后查找会向下遍历以选择唯一的h3。
任何帮助将不胜感激。
答案 0 :(得分:0)
我设法使用Simo Ahava的纯javascript选项以及来自this post的Stackoverflow用户贾斯汀的评论来实现这一目标
function() {
return function(target, selector) {
while (!target.matches(selector) && !target.matches('body')) {
target = target.parentElement;
}
return target.matches(selector) ? target : undefined;
}
}
function() {
var parentElement = {{Find Closest}}({{Click Element}}, 'div.field-item'),
childElement = typeof parentElement !== 'undefined' ? parentElement.querySelector('h3') : undefined;
return typeof childElement !== 'undefined' ? childElement.innerText : undefined;
}