JavaScript location.search 属性:设置或取得当前 URL 的查询字串

JavaScript location.search 属性

Location 对象的 search 属性用于设置或取得当前 URL 的查询字串(? 符号及后面的部分),语法如下:

location.search = search

  

location.search 实例

例子 1

该例子通过 location.search 属性得到当前 URL 的查询字串。

假设当前页面的 URL 是:http://www.5idev.com/p-javascript_location.shtml?part=1

<script type="text/javascript">

document.write(location.search);

</script>

  

运行该例子,输出:

?part=1

  

例子 2

该例子通过 location.search 属性来设置 URL 的查询字串。

假设当前页面的 URL 是:http://www.5idev.com/p-javascript_location.shtml?part=1

<html>

<script type="text/javascript">

function setSearch(){
    location.search = "?part=2";
}

</script>

<body>
<button onclick="setSearch()">设定查询字串</button>
</body>
</html>

  

运行该例子,点击 设定查询字串 按钮,触发 setSearch() 函数,浏览器地址栏的 URL 将变为:http://www.5idev.com/p-javascript_location.shtml?part=2,而浏览器也将访问该 URL。

 

 

原文链接:http://www.5idev.com/p-javascript_location_search.shtml

posted @ 2016-03-14 16:22  半前端半设计的四不像  阅读(890)  评论(0)    收藏  举报