jQuery - 我想将 html5 数据属性值从特定元素 class 拉入 onclick 属性值

jQuery - I want to pull html5 data-attribute values from a particular element class into an onclick attribute value

我正在分配 css class .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' });

数据属性和 classes 已正确添加。

现在,我正尝试通过执行 .attr('onclick', '_gaq.push('_trackEvent', ...') 以 class .ga-track 为目标的所有元素来嵌入内联 Google Analytics onClick 事件,如您在下面的片段。

$(".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'));
});

在添加 onclick="" 属性方面,.on 方法绝对优于 .attr 方法。

我还使用了 analytics.js 的错误 GA 方法,之前使用 _gaq.push 函数而不是 ga('send' ...)

试试这个,

$(".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'));
});

这样试试:

$(".gaTrack").click(function(){
   _gaq.push('_trackEvent', $(this).data('category'), $(this).data('action'), $(this).data('label'), $(this).data('value'), $(this).data('interaction'));
});

您不应将 onclick 属性与 jquery 一起使用,而应使用 .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'));
})

还有什么问题: