【问题标题】:How to redirect a page based on referring/current URLs with jQuery?如何使用 jQuery 基于引用/当前 URL 重定向页面?
【发布时间】:2015-01-16 20:01:32
【问题描述】:

所以这就是我所拥有的 - 我想使用或,但不是 100%。

if(document.location.href.indexOf('test/test/test1') > -1) { 
    document.location.href = 'http://www.test.com/thank-you';
}
if(document.location.href.indexOf('test/test/test9') > -1) { 
    document.location.href = 'http://www.test.com/thank-you';
}

会是:

if(document.location.href.indexOf('test/test/test1' || 'test/test/test9') > -1) { 
    document.location.href = 'http://www.test.com/thank-you';
}

【问题讨论】:

  • RegEx 已失效 - 真实 URL 差异太大(抱歉)。变量很好,但从长远来看会太多。看起来我重复如下所述。我简直不敢相信必须说两次 document.location.href.indexof ()。

标签: javascript jquery redirect


【解决方案1】:

应该是这样的:

if(document.location.href.indexOf('test/test/test1') > -1
  || document.location.href.indexOf('test/test/test9') > -1) {

}

【讨论】:

    【解决方案2】:

    你需要重复整个表达式:

    if(document.location.href.indexOf('test/test/test1'> -1 || document.location.href.indexOf('test/test/test1' > -1) { .....

    【讨论】:

      【解决方案3】:

      使用正则表达式可能更短更容易:

      var regex = /test\/test\/(test1|test9)/
      if (regex.test(document.location.href)) { 
        // do stuff
      }
      

      【讨论】:

        【解决方案4】:

        尝试使用变量:

        var found1 = document.location.href.indexOf('test/test/test1') > -1;
        var found9 = document.location.href.indexOf('test/test/test9') > -1;
        
        if(found1 || found9) {
            document.location.href = 'http://www.test.com/thank-you';
        }
        

        如果 url 中的 1 或 9 可能是其他东西,例如数字,您也可以使用正则表达式:

        var found = document.location.href.match(/\/test\/test\/test\d$/); // returns an array of matches.
        
        if(found) {
            document.location.href = 'http://www.test.com/thank-you';
        }
        

        【讨论】:

          【解决方案5】:

          你可以使用一个函数:

          // This function accepts an array as a parameter
          function findInURL(arr)
          {
              for(var i = 0; i < arr.length; i++)
                  if(document.location.href.indexOf(arr[i]) > -1)
                      return 1;
              return 0;
          }
          

          并像这样使用它:

          if(findInURL(['test/test/test1', 'test/test/test9', 'test/test/foo']))
              document.location.href = 'http://www.test.com/thank-you';
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-09-19
            • 2020-02-27
            • 2017-11-03
            • 1970-01-01
            • 1970-01-01
            • 2015-01-14
            • 1970-01-01
            相关资源
            最近更新 更多