Pregunta

I have this url:

csumb/index.php?page=consultanta 

I try to compare 2 links but this code do the same thing if I change my link and I refresh the page.

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

if(pathname == a) {
    $("body").html("rahat");
}
¿Fue útil?

Solución

There's multiple parts to location (or window.location, to use the literal reference):

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

Using console.log(location) directly into the Chrome console, it gives the following properties (plus some other stuff):

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"

What you're really after is:

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

The filename, if in the URL, will be in location.pathname, so index.php will not need to be added separately either.

Otros consejos

Try this:

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

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

It's not jQuery, please edit the title to javascript. the jQuery part is not used in if statement. window.location.pathname returns something like /csumb/index.php without parameters. so if you like to check the pathname with other parameters, you will need to do this :

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

You need to use the === operator and you need to add a "/".

Also you need 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");
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top