如何根据URL查询参数

时间:2016-07-14 12:51:48

标签: jquery

所以,我正在尝试使用jQuery来更改页面上的标题标记,具体取决于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>,或者转到除上述任何其他查询参数之外的任何其他查询参数。

如果你们能帮助我,我会非常感激。谢谢。

更新

已经能够弄清楚如何做到这一点。这是最理想的解决方案吗?

    $(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();
        }

    });

1 个答案:

答案 0 :(得分: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 $('#family')时获取id并相应地编码。

相关问题