【问题标题】:Jquery Redirect Based on URL location基于 URL 位置的 Jquery 重定向
【发布时间】:2013-03-28 13:37:09
【问题描述】:

这就是我要解决的问题......

  1. 仅当 URL 明确包含 mydomain.com 上的 /foldername/index.htm && /foldername/ 时,才会重定向到 http://www.example.com
  2. URL 是否应该包含 any URL 参数 /foldername/index.htm?例如它应该不重定向
  3. 所有其他 URL 不应重定向

这是我的 javascript,它不完整,但最终是我要解决的问题......

var locaz=""+window.location;
if (locaz.indexOf("mydomain.com") >= 0) {
    var relLoc = [
        ["/foldername/index.htm"],
        ["/foldername/"]
    ];
    window.location = "http://www.example.com"; 
}

这是为了管理一些用户基于特定方式(如书签)点击的 URL。在不删除页面的情况下,我们希望在采取进一步行动之前监控有多少人点击了该页面。

【问题讨论】:

  • 我用目的更新了描述

标签: javascript regex redirect


【解决方案1】:

页面不会总是在同一个域上,如果 url 包含/foldername/pagename.htm,它是否也已经包含/foldername?因此,&& 检查将是多余的。

试试下面的代码。

var path = window.location.pathname;

if  ( (path === '/foldername' || path === '/foldername/index.html') && !window.location.search ) {
    alert('should redirect');
} else {
    alert('should not redirect');
}

【讨论】:

  • jack,是的,它会在同一个域上,另外,我将页面名称的描述更新为“index.htm”,因为 /foldername/ 是没有 index.htm 的文件夹名称,因此应该有人访问他们将被重定向的文件夹名称或 index.htm。
  • 所以基本上你可以通过/foldername/foldername/index.html 访问index.html?
  • 是的,这是正确的。显然我们有将用户直接发送到 /foldername/ 的链接,这与点击 /foldername/index.htm 相同,但在文件夹名之后总是有一个 / 很好
  • location.pathname 不会包含 ? - 在 location.search 中可用。
  • @rodneyrehm 谢谢,当我更新我的答案时忽略了这一点。
【解决方案2】:
var url = window.location;
var regexDomain = /mydomain\.com\/[a-zA-Z0-9_\-]*\/[a-zA-Z0-9_\-]*[\/\.a-z]*$/    
if(regexDomain.test(url)) { 
  window.location = "http://www.example.com"; 
}

【讨论】:

  • 这看起来是为了解决参数和域,但当 URL 是明确的“/foldername/pagename.htm”或“/foldername/”时不是
【解决方案3】:

熟悉location 对象。它提供pathnamesearchhostname 作为属性,省去了RegExp 的麻烦(无论如何你最喜欢get wrong)。您正在寻找以下方面的内容:

// no redirect if there is a query string
var redirect = !window.location.search 
  // only redirect if this is run on mydomain.com or on of its sub-domains
  && window.location.hostname.match(/(?:^|\.)mydomain\.com$/)
  // only redirect if path is /foldername/ or /foldername/index.html
  && (window.location.pathname === '/foldername/' || window.location.pathname === '/foldername/index.html');

if (redirect) {
  alert('boom');
}

【讨论】:

    猜你喜欢
    • 2014-04-05
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-07
    相关资源
    最近更新 更多