我分配一个css类.ga-track
来指定我想要跟踪的元素,同时也将数据属性data-category=""
、data-action=""
、data-label=""
、data-value=""
等分配给特定的元素。
例子:
$('a, button, form, input').addClass('ga-track');
$('form#formid').attr({ 'data-category':'Form Submission', 'data-action':'Click', 'data-label':'Specific FormID Label' });
数据属性和类被正确地添加。
现在,我试图嵌入一个内联的Google事件,方法是通过执行.ga-track
类的所有元素,执行.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()
绑定到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'));
});
.on方法在添加onclick="“属性方面绝对优于.attr方法。
我在analytics.js中也使用了错误的GA方法,之前使用的是_gaq.push函数,而不是ga('send‘.)
发布于 2016-10-05 08:51:26
您不应该在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'));
})
还有什么问题:
$('.gaTrack')
搜索它(将找不到.)。$(this)
来引用$('.ga-track')
,但是this
可能是另外一些东西。读:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this发布于 2016-10-05 08:45:29
尝尝这个,
$(".gaTrack").on("click",function(){
_gaq.push('_trackEvent', $(this).data('category'), $(this).data('action'), $(this).data('label'), $(this).data('value'), $(this).data('interaction'));
});
或,
$(".gaTrack").click(function(){
_gaq.push('_trackEvent', $(this).data('category'), $(this).data('action'), $(this).data('label'), $(this).data('value'), $(this).data('interaction'));
});
发布于 2016-10-05 08:46:39
试着这样做:
$(".gaTrack").click(function(){
_gaq.push('_trackEvent', $(this).data('category'), $(this).data('action'), $(this).data('label'), $(this).data('value'), $(this).data('interaction'));
});
https://stackoverflow.com/questions/39879448
复制相似问题