0

我在 index.php 页面上有两个单独的表单:

<form action="search_results.php" method="get" id="search_housing_area">
  <input type="text" name="rent_housing" />
  <inout type="submit" name="search_housing" value="" />
</form>

<form action="search_results.php" method="get" id="search_rooms_area">
  <input type="text" name="rent_rooms" />
  <inout type="submit" name="search_rooms" value="" />
</form>

当我提交其中任何一个表单时,网址显示为:

http://www.domain.com/search_results.php?rent_housing=1234&search_housing=

或者

http://www.domain.com/search_results.php?rent_rooms=1234&search_rooms=

在 search_results.php 页面上,我有两个 div,#housing_results 和 #rooms_results。默认情况下,它们都是隐藏的。如果 GET 变量“search_housing”存在,我想显示 div#housing_results,如果 GET 变量“search_rooms”存在,我想显示 div#rooms_results。

如果 url 中存在特定的 GET 变量,如何使用 jQuery 制作特定的 div 显示?

4

4 回答 4

6
<?php
 $disp_div=0;
if(isset($_GET['search_housing']))
{
   $disp_div=1;
}
else if(isset($_GET['search_rooms']))
{
  $disp_div=2;
}
?>

jQuery代码

$(document).ready(function(){

var show=<?php echo $disp_div; ?>;

 if(show==1)
 {
   $('#div_search_housing').show();
 }
else if(show==2)
 {
   $('#div_search_rooms').show();
 }
});
于 2012-07-14T05:48:03.830 回答
2

您可以使用window.location和搜索query string.

var winLoc = window.location.search;
//will output ?rent_rooms=1234&search_rooms=

现在我们将删除 ?,拆分&符号上的字符串,并使其成为一个数组

winLoc = winLoc.replace('?', '').split('&');

var  ourStr = winLoc[1].replace('=', '');

switch(ourStr){
  case 'search_rooms':
    $('.switch').css('backgroundColor', 'red');
    break;
  case 'search_housing':
    $('.switch').css('backgroundColor', 'blue');
    break;       
}

这是一个带有预定义字符串的工作 jsFiddle,例如

于 2012-07-14T05:52:22.660 回答
1

这是一个纯 JS 解决方案。如其他答案中所述,还有一些方法可以使用 PHP 来做到这一点。

function stuff()
{
    var queryPairs = window.location.href.split('?').pop().split('&');
    for (var i = 0; i < queryPairs.length; i++)
    {
        var pair = queryPairs[i].split('=');
        if (pair[0] == 'search_housing')
        {
            $('#rooms_results').hide();
            $('#housing_results').show();
            return;
        }
        if (pair[0] == 'search_rooms')
        {
            $('#housing_results').hide();
            $('#rooms_results').show();
            return;
        }
     }
     // None of the two options exist in the query
}
于 2012-07-14T05:47:48.103 回答
0

您可以使用纯 JS:

function getParameterByName(name)
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search);
    if(results == null)
    return "";
    else
    return decodeURIComponent(results[1].replace(/\+/g, " "));
}  

这里

所以在你的情况下应该是这样的:

if (getParameterByName('search_housing').length > 0) { ... } 
if (getParameterByName('search_rooms').length > 0)  { ... } 
于 2012-07-14T05:52:23.030 回答