将变量传递给window.location href

3
我想在点击外链时延迟页面跳转,以便Google事件跟踪有足够的时间进行。我编写了下面的代码,但我不确定如何将我的变量传递给window.location。它只是将它作为字符串"url"添加,而不是链接地址。我做错了什么?
$("a.private-product-order-button").click(function(e) {
   e.preventDefault();
   _gaq.push(['_trackEvent', 'Order buttons', 'Click', 'Service']);
   var url = $(this).attr("href");
   setTimeout(function() {
      $(window.location).attr('href', 'url');
      }, 200);
});

window.location.href=url - 你过度使用jQuery了 - mplungjan
@mplungjan:这种事情真的可能吗? - Blender
3个回答

2

不需要使用jQuery来设置location对象的属性(也不需要使用jQuery来获取锚点对象的href属性):

$("a.private-product-order-button").click(function(e) {
    e.preventDefault();
    _gaq.push(['_trackEvent', 'Order buttons', 'Click', 'Service']);

    var url = this.href;
    setTimeout(function() {
        window.location.href = url;
    }, 200);
});

谢谢。我对这个非常新,按照“正确的方式”做事还在不断学习中。 - Johan Dahl

1
因为你最终是在添加字符串。
应该是这样的:
$(window.location).attr('href', url);

不是
$(window.location).attr('href', 'url');

哦,该死,这太容易了。谢谢。 - Johan Dahl

1

使用$(window.location).attr('href', url);,但不要在url周围添加引号。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接