4
$(document).on('click','a',function(e){
    e.preventDefault();

    var href = $(this).attr('href');

    sendAnalytics("clicked a link",function(){
        // on success callback, continue with link's redirect
        window.location = href;
        //   or location.assign(href);
    });

    setTimeout(function(){
        window.location = href;
    },5e3); // just incase callback never fires
});

在此示例中,如何模拟默认链接点击行为?我注意到,如果我在新选项卡(control+clickmiddle-click)中打开,它仍会重定向当前选项卡。

我知道我可以捕捉到每次点击并检测它是鼠标中键还是鼠标左键,但是有没有更简单的方法来实现这一点,包括诸如control+click


到目前为止,我看到的唯一选择是将值存储在 cookie 中,然后在每个页面加载时读取 cookie、发送分析并删除 cookie。

4

1 回答 1

0

As far as I understand, you're trying to intercept the link click event, send some analytics data, then recreate the click to continue with navigation. So, to do that:

function NewTab(url) {
    var newTab = window.open(url,"_blank");
    newTab.focus();
}

$("a").on("click", function(e) {    // more efficient

    var href = $(this).attr("href");

    if(e.ctrlKey) {   // ctrl to open in a new tab

        sendAnalytics("clicked a link", function() {
            NewTab(href);
        });

        setTimeout(function() {
            location.href = href;
        }, 5e3);
    }

    else {
        sendAnalytcis("clicked a link", function() {
            location.href = href;
        });

        setTimeout(function() {
            location.href = href;
        }
    }
});

First I create a new tab function that I can use if the user has control-clicked the link. Then I intercept the click, and if the Control key was pressed, I send analytics then open the link in a new tab. Otherwise, I send the analytics then redirect the current tab. The backups are still there in case the callback doesn't fire.

As a footnote, the simplest way to recreate a 'natural link click' is $(this).click();

Hope this helps!
-CE

于 2014-04-13T14:58:14.060 回答