Javascript A href同时单击和再次单击

Javascript A href同时单击和再次单击,javascript,jquery,html,Javascript,Jquery,Html,我使用onClick事件将数据层推送到Google Tag manager,但我还想使用a href将用户发送到页面。因此,我不认为我的事件被记录在谷歌分析中,因为在事件被记录之前,页面已经被重定向 JS HTML 您可以将用户重定向到函数中的页面: $(document).ready(function () { $('.gtm-click-evt').click(function(){ var dataAmount = $(this).data('value').replace("$"

我使用onClick事件将数据层推送到Google Tag manager,但我还想使用
a href
将用户发送到页面。因此,我不认为我的事件被记录在谷歌分析中,因为在事件被记录之前,页面已经被重定向

JS

HTML


您可以将用户重定向到函数中的页面:

$(document).ready(function () {
$('.gtm-click-evt').click(function(){
    var dataAmount = $(this).data('value').replace("$", ""); //Remove dollar sign
    var value = parseInt(dataAmount); //convert to int
    dataLayer.push({
        'event': 'clickEvent',
        'category': $(this).data('category'),
        'action': $(this).data('action'),
        'label': $(this).data('label'),
        'value': value
    });
    window.location = "/want-to-also-redirect-to-a-page";
  });
});
然后链接会发生变化:

<a class="gtm-click-evt gtm-colo btn btn-primary bg-green"
    data-category="productClick"
    data-action="colocationClick"
    data-label="label"
    data-value="99">
    Buy Now
</a>

立即购买
停止默认操作(event.preventDefault();)运行基本代码,然后等待一秒钟并重定向

$(document).ready(function () {
$('.gtm-click-evt').click(function(event){
    event.preventDefault();
    var dataAmount = $(this).data('value').replace("$", ""); //Remove dollar sign
    var value = parseInt(dataAmount); //convert to int
    dataLayer.push({
        'event': 'clickEvent',
        'category': $(this).data('category'),
        'action': $(this).data('action'),
        'label': $(this).data('label'),
        'value': value
    });
     url=$(this).attr('href');
    setTimeout(function(){location.href = url}, 1000);
});
});

位置将根据按钮的不同而变化,因此我不想将其编码到方法中。我只想将GTM数据层事件与站点导航分离,而不将其包含在function@ottz0由于您使用元素选择来查找这些链接,因此还可以将目的地存储在
数据
值中,并在函数中动态地将用户发送到那里。例如,
data dest=“/want-to-allow-redirect-to-a-page”
window.location=$(this).data('dest')
。根据我自己的评论,此方法仍然可以在触发事件之前停止操作。重定向应使用
eventCallback
函数进行操作,但您还需要考虑GTM被广告或跟踪拦截器阻止的情况。href标记仍会首先被触发,因为我将1000改为10000,页面会直接启动,无需等待,因此未点击prevent.defaultOk,感谢这项工作……为了让它工作,我将setTimeout更新为函数setTimeout(function(){location.href=url},1000);
<a class="gtm-click-evt gtm-colo btn btn-primary bg-green"
    data-category="productClick"
    data-action="colocationClick"
    data-label="label"
    data-value="99">
    Buy Now
</a>
$(document).ready(function () {
$('.gtm-click-evt').click(function(event){
    event.preventDefault();
    var dataAmount = $(this).data('value').replace("$", ""); //Remove dollar sign
    var value = parseInt(dataAmount); //convert to int
    dataLayer.push({
        'event': 'clickEvent',
        'category': $(this).data('category'),
        'action': $(this).data('action'),
        'label': $(this).data('label'),
        'value': value
    });
     url=$(this).attr('href');
    setTimeout(function(){location.href = url}, 1000);
});
});