【问题标题】:Passing variable to window.location href [duplicate]将变量传递给 window.location href [重复]
【发布时间】:2013-01-28 19:28:10
【问题描述】:

我试图在点击时延迟传出链接,以便谷歌事件跟踪有时间发生。

我编写了以下代码,但不确定如何将变量传递给 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 - 你已经结束了 jQuerying
  • @mplungjan:这样的事情可能吗?

标签: jquery redirect settimeout window.location


【解决方案1】:

无需使用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);
});

【讨论】:

  • 谢谢。我对此很陌生,以“正确的方式”做事是一项正在进行的工作。
【解决方案2】:

因为你毕竟是在添加字符串。

应该是:

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

不是

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

【讨论】:

  • 哦,该死的太容易了。谢谢。
【解决方案3】:

使用$(window.location).attr('href', url);,不带url 引号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-11
    • 2016-02-23
    • 2012-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多