0
if(document.URL!="location.php?img_url="+img_url){
        window.location.href = "location.php?img_url="+img_url;
    }

这会不断重新加载页面。我检查 url 看它是否改变,它没有。

4

6 回答 6

7

因为看看是什么document.URL

console.log(document.URL);

它返回完整的网址。http://example.com/location.php?img_url=1234

您正在寻找完全匹配,而不是部分匹配。

一种解决方案是使用indexOf()

if(document.URL.toLowerCase().indexOf("location.php?img_url="+img_url)===-1){
于 2013-06-26T15:17:17.223 回答
3

!=总是正常工作。是你做错了!

在这种情况下,问题在于您期望document.URL成为您设置的字符串window.location.href。很可能不是。

确实,永远不会"location.php?img_url="+img_url。它始终是完整的URL,因此类似于http://www.example.com/location.php?img_url="+img_url.

于 2013-06-26T15:19:14.463 回答
2

尝试

if(window.location != "http://www.urlhere.com/location.php?img_url="+img_url){
    window.location.href = "http://www.urlhere.com/location.php?img_url="+img_url;
}
于 2013-06-26T15:18:31.927 回答
1

使用document.location.pathname + document.location.search代替document.URL

于 2013-06-26T15:25:36.253 回答
0

尝试使用

window.location.pathname

而不是使用

document.URL
于 2013-06-26T15:17:59.647 回答
0

也许您只是忘记了域名。

尝试这样的事情:

if(document.URL!="http://localhost/location.php?img_url="+img_url){
    window.location.href = "http://localhost/location.php?img_url="+img_url;
}
于 2013-06-26T15:20:20.473 回答