自己写的一个js获取首页地址(路径)的方法

    <script type="text/javascript">
        function getIndexURL(myObject, myURL) {
            var hostname = window.location.hostname;
            var port = window.location.port;
            if (port == null) {
                var r_str = "http://" + hostname + "/" + myURL;
                return $(myObject).attr("href", r_str);
            } else {
                var r_str = "http://" + hostname +":"+ port + "/" + myURL;
                return $(myObject).attr("href", r_str);
            }
        }
</script>

  数据调用时:

方法一

        <a id="A1" target="_blank" onclick="getIndexURL('#A1','web/detail.aspx?cid=201');">我的链接</a>

方法二

        <a id="A1" target="_blank">我的链接</a>
        <script>
            getIndexURL("#A1", "web/detail.aspx?cid=201");
        </script>

  

参考:

JQUERY获取当前页面的URL信息

设置或获取对象指定的文件名或路径。
window.location.pathname

设置或获取整个 URL 为字符串。
window.location.href

设置或获取与 URL 关联的端口号码。
window.location.port

设置或获取 URL 的协议部分。
window.location.protocol

设置或获取 href 属性中在井号“#”后面的分段。
window.location.hash

设置或获取 location 或 URL 的 hostname 和 port 号码。
window.location.host

设置或获取 href 属性中跟在问号后面的部分。
window.location.search

window.location

属性描述
hash 设置或获取 href 属性中在井号“#”后面的分段。
host 设置或获取 location 或 URL 的 hostname 和 port 号码。
hostname 设置或获取 location 或 URL 的主机名称部分。
href 设置或获取整个 URL 为字符串。
pathname 设置或获取对象指定的文件名或路径。
port 设置或获取与 URL 关联的端口号码。
protocol 设置或获取 URL 的协议部分。
search 设置或获取 href 属性中跟在问号后面的部分。

方法三:自建类库

    public class urlFormat
    {
        public static string IndexURL(){
            string u_hostname = HttpContext.Current.Request.Url.Host;
            int u_port = HttpContext.Current.Request.Url.Port;

            if (u_port.ToString() != null || u_port.ToString() != "")
            {
                return "http://" + u_hostname + ":" + u_port + "/";
            }
            else return "http://" + u_hostname + "/";
        }
    }
技术文档
原文地址:https://www.cnblogs.com/ishibin/p/2801749.html