繁体   English   中英

基于URL位置的jQuery重定向

[英]Jquery Redirect Based on URL location

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

  1. 仅当URL在mydomain.com上显式包含/foldername/index.htm && / foldername /时,才重定向到http://www.example.com
  2. URL是否应包含任何 URL参数/foldername/index.htm?例如,不应重定向
  3. 其他所有网址均不应重定向

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

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

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

页面不会始终位于同一域中,如果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');
}
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"; 
}

熟悉位置对象。 它提供pathnamesearchhostname作为属性,从而避免了RegExp的麻烦(无论如何,您最想出错 )。 您正在寻找以下方面的东西:

// 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');
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM