【问题标题】:If statement not work jquery如果语句不起作用jquery
【发布时间】:2013-01-12 10:50:00
【问题描述】:

我有这个网址:

csumb/index.php?page=consultanta 

我尝试比较 2 个链接,但如果我更改链接并刷新页面,此代码会执行相同的操作。

var pathname = window.location.pathname;
var a = "csumb/index.php?page=consultanta";

if(pathname == a) {
    $("body").html("rahat");
}

【问题讨论】:

  • 你试过console.log(pathname);看看里面到底有什么吗?我怀疑您在字符串的开头缺少斜杠。
  • location.pathname 为您提供路径,例如/?page=consultanta 是一个查询字符串
  • 在此处查看您在 JS 中可以访问的 URL 的不同部分:stackoverflow.com/questions/6944744/…

标签: javascript jquery if-statement pathname


【解决方案1】:

location(或window.location,使用字面引用)有多个部分:

https://packagist.org/search/?search_query%5Bquery%5D=symfony

直接在 Chrome 控制台中使用console.log(location),它会提供以下属性(以及其他一些东西):

hash: ""
host: "packagist.org"
hostname: "packagist.org"
href: "https://packagist.org/search/?search_query%5Bquery%5D=symfony&page=4"
origin: "https://packagist.org"
pathname: "/search/"
port: ""
protocol: "https:"
search: "?search_query%5Bquery%5D=symfony&page=4"

你真正追求的是:

var pathname = location.pathname + location.search;
var a = "/csumb/index.php?page=consultanta";
//       ^ Note the / at the beginning

文件名,如果在 URL 中,将在 location.pathname 中,因此 index.php 也不需要单独添加。

【讨论】:

    【解决方案2】:

    试试这个:

    var pathname = window.location.pathname;
    var search = window.location.search;
    var a = "/csumb/index.php?page=consultanta";
    
    if((pathname + search) == a) {
        $("body").html("rahat");
    }
    

    【讨论】:

    • location.pathname 不包含任何 URL 变量,因此这不起作用。
    • 我尝试了您的代码,但不同页面的结果相同。
    • 你能把这行加到代码里,然后把日志给我。 console.log(document.location);
    【解决方案3】:

    这不是 jQuery,请将标题编辑为 javascript。 if 语句中不使用 jQuery 部分。 window.location.pathname 返回类似 /csumb/index.php 的内容,不带参数。所以如果你想用其他参数检查路径名,你需要这样做:

    var path = window.location.pathname + window.location.search; 
    

    【讨论】:

    • 我试过这个:var pathname = window.location.pathname; var search = window.location.search; var a = "localhost/csumb/index.php?page=consultanta"; if((路径名 + 搜索) == a) { $("#outPopUp").fadeIn(3000); } 其他 { $("#outPopUp").fadeOut(3000); }
    • 你不应该使用 localhost !试试这段代码: var pathname = window.location.pathname; var search = window.location.search; var a = "/csumb/index.php?page=consultanta"; if((路径名 + 搜索) == a) { $("body").fadeIn(3000);alert ('ee'); } else { $("body").fadeOut(3000); }
    【解决方案4】:

    您需要使用=== 运算符并且您需要添加一个“/”。

    你还需要window.location.search:

    var a = "/csumb/index.php?page=consultanta";
    var search = window.location.search;
    var pathname = window.location.pathname;
    
    if(pathname + search === a) {
        $("body").html("rahat");
    }
    

    【讨论】:

    • 从答案中删除了
    猜你喜欢
    • 2014-09-10
    • 2012-12-26
    • 2013-06-20
    • 2013-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多