在Google Tag Manager中实现兼容IE9的带H1标题的Read more点击追踪
修正方案:解决GTM中无法获取对应H1标题的问题
先拆解你现有代码里几个导致失败的核心问题,再一步步给出修正方案:
问题1:函数定义顺序错误
你把getClosest函数定义在了if代码块内部,当第一次执行getClosest(event.target, '.parent-column')时,这个函数还未被定义,直接会抛出错误,导致后续逻辑完全无法执行。
问题2:选择器不匹配
你用了.parent-column作为目标容器,但提供的HTML里根本没有这个类名!根据你的页面结构,应该定位到最外层的列容器(比如带有portlet-column类的div),才能找到同一区块内的H1。
问题3:变量作用域与IE9兼容问题
- 未用
var声明labelh1,会产生全局变量风险; - IE9中
textContent对部分元素支持不佳,需要兼容innerText。
问题4:GTM中事件元素的引用
在GTM的自定义JS变量里,用{{Click Element}}获取点击元素比直接用event.target更可靠,能避免事件冒泡导致的目标元素偏差。
修正后的完整代码
function() { // 先定义getClosest函数,确保调用前已存在 var getClosest = function(elem, selector) { // IE9兼容的matches方法polyfill if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.msMatchesSelector || function(s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; } // 向上遍历DOM树找匹配的元素 for (; elem && elem !== document; elem = elem.parentNode) { if (elem.matches(selector)) return elem; } return null; }; var clickText = {{Click Text}}; // 只处理Read more..的点击 if (clickText.trim() === "Read more..") { // 找到最外层的列容器(匹配HTML里的实际类名) var parentColumn = getClosest({{Click Element}}, '.portlet-column'); if (parentColumn) { // 在列容器内找到H1元素 var heading = parentColumn.querySelector('h1'); if (heading) { // 兼容IE9的文本获取:优先用textContent,降级到innerText var headingText = heading.textContent || heading.innerText; // 组合成目标格式,去除多余空格 return clickText.trim() + " | " + headingText.trim(); } } // 找不到H1时返回原始文本作为兜底 return clickText; } // 非Read more..链接直接返回点击文本 return clickText; }
关键修改说明
- 调整函数定义顺序:把
getClosest移到最顶部,确保调用前函数已存在; - 修正选择器:用
.portlet-column替换.parent-column,匹配你页面里的实际容器类; - 优化变量处理:用
var声明所有变量,避免全局污染,同时对文本做trim()处理,避免HTML空格影响判断; - IE9兼容优化:简化
matches的polyfill,只保留IE9需要的msMatchesSelector,文本获取兼容textContent和innerText; - 增加容错处理:如果找不到父容器或H1,返回原始点击文本,避免GTM变量报错;
- GTM元素引用:用
{{Click Element}}获取点击元素,比event.target更稳定。
内容的提问来源于stack exchange,提问作者Bastiaan
相关产品推荐
相关产品推荐

