js中location对象方法怎么使用

2023-10-27,

本篇内容主要讲解“js中location对象方法怎么使用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“js中location对象方法怎么使用”吧!

1、location对象方法

是一个URL操作方法,表示载入窗口的URL;

是window对象和document对象的属性,可以通过window.location属性来访问;

可以获取URL的参数并解析URL。

2、使用语法

location.[属性|方法]

3、locatio对象常用属性

console.log(location.hash);
console.log(location.host);
console.log(location.hostname);
console.log(location.href);
console.log(location.pathname);
console.log(location.port);
console.log(location.protocol);
console.log(location.search);

4、使用js中location对象方法获取URL参数

    <div></div>
<script>
        console.log(location.search); // ?uname=andy
        // 1.先去掉?  substr('起始的位置',截取几个字符);
        var params = location.search.substr(1); // uname=andy
        console.log(params);
        // 2. 利用=把字符串分割为数组 split('=');
        var arr = params.split('=');
        console.log(arr); // ["uname", "ANDY"]
        var div = document.querySelector('div');
        // 3.把数据写入div中
        div.innerHTML = arr[1] + '欢迎您';
</script>

到此,相信大家对“js中location对象方法怎么使用”有了更深的了解,不妨来实际操作一番吧!这里是本站网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

《js中location对象方法怎么使用.doc》

下载本文的Word格式文档,以方便收藏与打印。