使用:js 中 url 傳參

Location 屬性

操作

代碼

輸出結果

獲取 # 號後面的字符串

window.location.hash

#/lingshoustatis/?starttime=2018-11-21&&endtime=2018-11-21

獲取 url 協議部分

window.location.protocol

http:

獲取 href  屬性中 ‘?’後的部分,又稱爲查詢字選集串

window.location.search

"?name=kang&when=2011"

獲取端口號

window.location.port

8000

獲取整個 url 字符串

window.location.href

http://localhost:8000/bui/#/lingshoustatis/?starttime=2018-11-21&&endtime=2018-11-21

獲取對象指定文件名或者路徑

window.location.pathname

/bui/

獲取 location 或 URL 的 hostname 和 port 號碼

window.location.host

localhost:8000

 

獲取 URL 方法

function GetQueryString(name){

   var after = window.location.hash.split("?")[1];

   if(after){

     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");

     var r = after.match(reg);

     if(r != null){

         return  decodeURIComponent(r[2]);

     }

     else {

         return null;

     }

   }

}

 

decodeURIComponent() 函數 是對url 進行解析

unescape() 函數可對通過 escape() 編碼的字符串進行解碼。

 

window.location和document.location互相等價的,可以交換使用

 

location的8個屬性都是可讀寫的,但是隻有href與hash的寫纔有意義。例如改變location.href會重新定位到一個URL,而修改location.hash會跳到當前頁面中的anchor(<a id="name">或者<div id="id">等)名字的標記(如果有),而且頁面不會被重新加載

 

場景一:假設url 是 http://b.a.com:88/index.php?name=kang&how=#when=2011#first

search:"?name=kang&how="     第一個"?"之後

hash:"#when=2011#first"           第一個"#"之後的內容

 

爲什麼有時候window.location.search 輸出是空呢?

注意上面的search和hash的區別,如果URL中“?”之前有一個“#”比如:“http://localhost:63342/index.html#/version?type=35&id=5”那麼使用window.location.search得到的就是空(“”)。因爲“?type=35&id=5”串字符是屬於“#/version?type=35&id=5”這個串字符的,也就是說查詢字符串search只能在取到“?”後面和“#”之前的內容,如果“#”之前沒有“?”search取值爲空。

 

應用1:鏈接帶參跳轉(react中操作)

    

    A 頁面:

             '1': `lingshoustatis/?starttime=${this.state.starttime}&&endtime=${this.state.endtime}`,

 

    B頁面:

             調用 GetQueryString 方法,然後傳值,要和 A 頁面上的 參數名相對應該,

           如下操作:

           var a = GetQueryString('starttime');

           var b = GetQueryString('endtime')

 

應用1:鏈接中跳轉到 tabs 頁面的第二個(react中操作)

 

    A頁面:

             

 

            

 

    B頁面:

    步驟:進來頁面接收 name,保存name值到state裏,然後 設置tabs 的 activeKey 屬性 ,激活 那個你需要展示的tab標籤 。

 

            1、在生命週期 ComponentDidMount 中獲取瀏覽器上的參數。

                decodeURIComponent(window.location.hash.match(/name=(\w+)/g)).match(/=(\w+)/)[1]

    

            2、因爲 tabs 有三個頁面。每個頁面都有一個 key 值,在 Tabs 上加屬性  activeKey={key} 。激活 那個你需要展示的tab標籤

                <Tabs  onChange={this.callback}   className='task'   activeKey={key}     tabBarExtraContent={operations}>

                         <TabPane tab=“第一個頁面" key="1"></TabPane>

                         <TabPane tab=“第二個頁面" key="2"></TabPane>

                         <TabPane tab=“第三個頁面" key="3"></TabPane>

                </Tabs>

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章