【问题标题】:Check url stored in variable to current url检查存储在变量中的 url 到当前 url
【发布时间】:2012-06-02 02:24:48
【问题描述】:

我不知道为什么这不起作用:

var myurl = "http://domain.com";
var currenturl = $(location).attr('href');
if (myurl == currenturl) {
...

myurl 和 currenturl 都是一样的,但是 if 语句中的脚本没有被执行。

编辑:

$(document).ready(function(){
var myurl = "http://domain.com";
var currenturl = window.location.href;
//alert(currenturl);
    if (myurl === currenturl) {
        alert('should see this');
    } else {
    }
});

解决方案:

$(document).ready(function(){
var myurl = "http://domain.com/"; // see the slash at the end
    if (myurl == location.href) {
        alert('that ss the same page');
    } else {
    }
});

有什么建议吗? 谢谢。

【问题讨论】:

  • 什么是location?是window.location吗?
  • 或者您在寻找 $("#location")?
  • 你的意思是window.location.href
  • 添加了完整的 sn-p,不起作用。 currenturl 应该是访问者所在的页面。

标签: jquery url location href attr


【解决方案1】:

这无论如何都行不通,因为您无法在 JavaScript 中像那样比较对象。 $(location) 几乎可以肯定是未定义的事实将是一个问题。见:Object comparison in JavaScript

如果您使用的是本地文件,则应在 URL 中添加“file://”

<html>
<script src="https://www.google.com/jsapi"></script>
<script>
google.load('jquery', '1.7.2');
</script>

<script>

$(document).ready(function(){
var myurl = "file://somedir/test.html";
var currenturl = window.location.href;
//alert(currenturl);
    if (myurl === currenturl) {
        alert('should see this');
    } else {
        alert ('see other thing');
    }
});


</script>
<body>
hi
</body>
</html>

【讨论】:

  • 实际上,$(location).attr('href') 确实有效……但不确定它是如何跨浏览器的;并没有消除它只是愚蠢的事实
  • 我刚刚用$(location).attr('href') 尝试过,它可以工作,也可以用location.href 尝试过,效果也很好。
【解决方案2】:

您不必为此使用 jQuery,只需:

if (myurl == location.href) {
    // the same
}

如果这不起作用,请通过调试它们的值来确保它们相同:

console.log(myurl, location.href);

【讨论】:

  • 谢谢,这行得通:myurl 缺少 / 而 location href 有。
  • @elbatron 很高兴听到您发现问题 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-06
  • 2018-11-11
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多