Get current URL with jQuery?

后端 未结 30 2221
你的背包
你的背包 2020-11-22 02:44

I am using jQuery. How do I get the path of the current URL and assign it to a variable?

Example URL:

http://localhost/menuname.de?foo=bar&nu         


        
30条回答
  •  清酒与你
    2020-11-22 03:04

    All browsers support Javascript window object. It defines the window of the browser.

    The global objects and functions become part of the window object automatically.

    All global variables are window objects properties and all global functions are its methods.

    The whole HTML document is a window property too.

    So you can use window.location object to get all url related attributes.

    Javascript

    console.log(window.location.host);     //returns host
    console.log(window.location.hostname);    //returns hostname
    console.log(window.location.pathname);         //return path
    console.log(window.location.href);       //returns full current url
    console.log(window.location.port);         //returns the port
    console.log(window.location.protocol)     //returns the protocol

    JQuery

    console.log("host = "+$(location).attr('host'));
    console.log("hostname = "+$(location).attr('hostname'));
    console.log("pathname = "+$(location).attr('pathname')); 
    console.log("href = "+$(location).attr('href'));   
    console.log("port = "+$(location).attr('port'));   
    console.log("protocol = "+$(location).attr('protocol'));

提交回复
热议问题