【问题标题】:what return 'windows.location.pathname'?什么返回'windows.location.pathname'?
【发布时间】:2015-12-27 20:47:30
【问题描述】:

我用函数 window.locatin.pathname 测试了一些东西。

这是我的 js 脚本:

var location = window.location.pathname;

console.log(location); // -> /de/immobilien-auf-mallorca/

if(location == "/de/immobilien-auf-mallorca"){
  console.log('true'); //doesn't work! It is not true???
}else{
  console.log('false'); //Output in my console    
}

我认为我的 var 'location' 是一个字符串并且包含这个字符串 '/de/immobilien-auf-mallorca'。

但如果我包含一个 if 语句 (if location = /de/immobilien-auf-mallorca),我不会进入我的 if 语句的第一部分。 (看上面)

我不知道为什么我的变量可能不是字符串?!

也许有人对此了解更多。

感谢您的帮助!

【问题讨论】:

  • 试试if(decodeURIComponent(location) == "/de/immobilien-auf-mallorca"){
  • 试过你的代码。对我来说很好。
  • @cgee 检查length 的路径名和要比较的字符串长度
  • @Tushar window.location = 28 和 if 语句中的字符串 = 27.. 但是为什么???
  • @cgee 不能从这里说可能隐藏的字符,请在位置尝试trim

标签: javascript if-statement pathname


【解决方案1】:

您选择了一个非常特殊的保留关键字来记录 ---> location,location 默认为 window.location,它是一个对象。 解决方案非常简单,将变量名替换为“myLocation”之类的名称即可。

var myLocation = window.location.pathname;

console.log(myLocation); // -> /de/immobilien-auf-mallorca

if(myLocation == "/de/immobilien-auf-mallorca"){
  console.log('true'); //It's going to work....
}else{
  console.log('false'); //Output in my console    
}

【讨论】:

    【解决方案2】:

    试试下面的代码:

    var locationVar = window.location.pathname;
    
       console.log(locationVar); // -> /de/immobilien-auf-mallorca
    
     if(locationVar == "/de/immobilien-auf-mallorca"){
          console.log('true'); //doesn't work! It is not true???
        }else{
          console.log('false'); //Output in my console    
        }
    

    希望这会对你有所帮助。

    【讨论】:

    • window.location.pathname 是一个对象。 不,它是字符串。尝试在控制台中关注> typeof window.location.pathname "string" > typeof location.pathname "string"
    • 如果我尝试它,我会收到消息,该位置未定义。
    • 别忘了声明位置变量。请参阅我的更新答案。
    • @Shahid 现在var location = window.location.pathname;,您正在访问location.pathname,这将是undefined
    • @Tushar 你是对的。实际问题在于变量名称位置。我已经更新了我的答案。
    猜你喜欢
    • 2013-09-05
    • 2017-07-23
    • 2011-01-05
    • 2012-01-15
    • 2020-06-02
    • 2019-09-28
    • 2015-09-06
    • 2011-07-30
    • 2011-11-01
    相关资源
    最近更新 更多