当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Creating a data-track Attribute that jQuery binds to for tracking data

问题描述:

Here's what I'm thinking about doing. using a data-track attribute in links and buttons that would contain data I want to send to Mixpanel... Something like:

click it

Then somehow jQuery bind to any click that contains the data-track. Or maybe bind to all clicks and if the item contains a data-track attribute, take the value and submit to mixpanel like so:

mpq.track("Open slideshow", {'show': 'Xmas'}, function(){ myfunction() });

Possible? Good idea? Bad idea? Any ideas on how to implement without requiring a ton of code?

Thanks

网友答案:

try this selector $('.YourClass[data-track]')

网友答案:

Sorry to resurrect, but here is an (untested) solution that should work. You can specify the event name using the data-track property, and any additional event attributes using a JSON string in the data-track-attrs property. The javascript will bind to the click handler for any element with a data-track property and dispatch the event to Mixpanel. In the case where a native JSON decoder is not available, it will fail silently.

<div class="header">
  <a href="#" data-track="Login" data-track-attrs='{ "where": "header" }'>login</a>
</div>

<a href="#" data-track="Open slideshow" data-track-attrs="{ show: 'Xmas' }">open xmas</a>

<div class="footer">
  <a href="#" data-track="Login" data-track-attrs='{ "where": "footer" }'>login</a>
</div>

<script type="text/javascript">
  $(function() {
    $("body").on('click', '[data-track]', function(evt) {
      var event_name = $(this).data('track');
      var event_attrs;
      try {
        event_attrs = JSON.parse($(this).data('track-attrs'));
      } catch(e) {}

      mixpanel.track(event_name, event_attrs);

    });
  });
网友答案:

Super late answer to an old question, but here's a jQuery plugin that does exactly that (and a lot more): http://os.lucidfusion.com/datatrack/

分享给朋友:
您可能感兴趣的文章:
随机阅读: