2016-07-14 114 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

相关问题