我正在分配一个 css 类 .ga-track
来指定我想要跟踪的元素,同时还分配数据属性 data-category=""
, data-action=""
、data-label=""
、data-value=""
等也适用于特定元素。
示例:
$('a, button, form, input').addClass('ga-track');
$('form#formid').attr({
'数据类别':'表单提交',
'data-action':'点击',
'data-label':'特定 FormID 标签'
});
数据属性和类已正确添加。
现在我尝试通过 .attr('onclick', '_gaq.push( '_trackEvent', ...')
如您在下面的代码片段中所见。
$(".ga-track").attr("onclick", _gaq.push('_trackEvent', $(this).data('category'), $(this).data('action'), $(this).data('label'), $(this).data('value'), $(this).data('interaction')););
我不确定在 .attr() 函数中调用数据属性的能力。
我还尝试执行 .attr('onclick', myFunction())
然后将 myFunction()
绑定(bind)到 jQuery 中的 _ga.push 调用,但它看起来就像我被迫附加一个 onclick 事件,并将 onclick 事件设置为与我尝试定位的元素内联。
编辑
这是我最终的工作代码:
$('.ga-track').on('click', function(){
ga('send', $(this).data('category'), $(this).data('action'), $(this).data('label'), $(this).data('value'), $(this).data('interaction'));
});
在添加 onclick=""属性方面,.on 方法绝对优于 .attr 方法。
我还对 analytics.js 使用了错误的 GA 方法,之前使用的是 _gaq.push 函数而不是 ga('send' ...)
最佳答案
你不应该使用 jquery 的 onclick
属性,而是使用 .click()
函数或 .on('click',..)
和一个回调函数:
$('.ga-track').on('click', function(){
_gaq.push('_trackEvent', $(this).data('category'), $(this).data('action'), $(this).data('label'), $(this).data('value'), $(this).data('interaction'));
})
还有什么问题:
您使用了 '.addClass('ga-track');'声明类名,但
$('.gaTrack')
搜索它(不会找到...)。您使用
$(this)
来引用$('.ga-track')
,但是this
可能是别的东西。阅读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
关于javascript - jQuery - 我想将特定元素类中的 html5 数据属性值提取到 onclick 属性值中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39879448/