2016-07-14 113 views
-1

因此,我試圖使用jQuery來更改我的頁面上的標題標記,具體取決於在URL中傳遞的查詢參數。如何根據URL查詢參數更改頁面標題

可能的URL參數可能如下:

http://example.com/ 
http://example.com?type=friends 
http://example.com?type=honeymoon 
http://example.com?type=family 

以下是標題標籤,我會隱藏與基於查詢通過展示。

<h2 id="default">Bali Vacations</h2> 
<h2 id="friends">Friends</h2> 
<h2 id="honeymoon">Honeymoon</h2> 
<h2 id="family">Family</h2> 

我想只顯示<h2 id="default"></h2>當用戶訪問只有域或去其他任何的查詢參數除了上面提到的那些。

如果你們能幫助我,我會很感激的。謝謝。

UPDATE

已經能夠找出如何做到這一點。這是最理想的解決方案嗎?

$(document).ready(function() { 
     // If no URL Query Param 
     if(location.search == ""){ 
      $('.default_name').show(); 
     } 
     // If honeymoon is query param 
     else if(location.search == "?type=honeymoon"){ 
      $('#honeymoon').show(); 
     } 
     // If family is query param 
     else if(location.search == "?type=family"){ 
      $('#family').show(); 
     } 
     // If friends is query param 
     else if(location.search == "?type=friends"){ 
      $('#friends').show(); 
     } 
     // Any other query param 
     else { 
      $('.default_name').show(); 
     } 

    }); 
+0

顯示現有的代碼 – ADyson

+0

@Justinas - 已經領先更新了我的代碼是這樣做或最好的方法有更好的方式?謝謝 –

回答

0
var url = window.location.href; //get the url 
var param = url.split('=')[1]; //split the url and get the parameter 
$('#default').text(param) //set the text to url parameter 
$('#default').attr('id',param); //now change the id from default to param 

我使用jQuery寫所需的代碼!使用不同的可能條件(如:。當越來越id爲家庭$('#family')並相應代碼ID

相關問題