正确的方式来跟踪链接'

Proper way to track link's click

本文关键字:链接 跟踪 方式      更新时间:2023-09-26

我正试图找到最详尽/兼容的解决方案来跟踪我的网站内的一些链接。

实际上,我有这样的代码:

$(".article-content a").each(function() {
    $(this).click(function() {
        // Tracking code here
    });
});

对于实际用户重定向处理有什么建议吗?我认为我们必须首先排除右键?还要确保Ctrl-Click,鼠标滚轮- click,触摸事件,键盘导航等…是否正确处理以触发,例如GA事件?

设置如下

$('.asdfasdf').mousedown(function(e) {
    switch (e.which) {
        case 1:
            //Left Mouse button pressed
            break;
        case 2:
            //Middle Mouse button pressed
            break;
        case 3:
            //Right Mouse button pressed
            break;
        default:
            //asdfasdf
    }
});
jQuery-Doc

使用带参数的函数来处理点击

$(".article-content a").each(function() {
    $(this).click(function(e) {
      if(e.ctrlKey) {
        //Ctrl+Click
      }
      if(e.altKey) {
        //Alt+Click
      }
      ...
    });
});

log e到控制台获取更多信息

您可以监听移动设备的其他事件:tap, taphold, swipe, swipeleft...

$(".article-content a").on("tap",function(){
  #element is tapped
});

尝试将jQuery的event.which.mousedown结合使用。比如:

$('.article-content a').mousedown(function(event){
    var message = 'click';
    if (event.ctrlKey) message += ' ctrl';
    if (event.shiftKey) message += ' shift';
    switch (event.which) {
        case 1:
           message = 'left ' + message;
           break;
        case 2:
           message = 'middle ' + message;
           break;
        case 3:
           message = 'right ' + message;
           break;
    }
    alert(message);
});

我建议您采用以下方法。

  1. 为要跟踪的元素添加一个类:

      < a class="trackMouseClick" >I want to be tracked onclick< / a >
    
  2. 定义每个类的事件处理程序:

    //the actual event handler
    //here you can implement the logic for each kind of event
    function mousedownHandler(e){
        console.log('target element: ' + e.target + ''tbutton clicked: ' + e.which);
    }
    //the event binder
    //remark: the event is bound only for the elements feature the proper class
    $('.trackMouseClick').on('mousedown',function(e){
        mousedownHandler(e);
    });
    
  3. 添加尽可能多的类和事件处理程序,尽可能多的事件你想要跟踪:

    function mousedownHandler(e){
        console.log('target element: ' + e.target + ''tbutton clicked: ' + e.which);
    }
    function tapHandler(e){
        console.log('target element: ' + e.target);
    }
    
    $('.trackMouseClick').on('mousedown',function(e){
        mousedownHandler(e);
    }).on('tap',function(e){
        tapHandler(e);
    });
    

主要优点是:

  • 模块化:你可以简单地从DOM元素中添加和删除类来添加和删除事件处理程序

  • 解耦:使用类将DOM结构与你要实现的跟踪逻辑分离