我在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=
OR
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。
如果网址中存在特定的GET变量,如何使用jQuery制作特定的div节目?
答案 0 :(得分: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();
}
});
答案 1 :(得分: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;
}
<强> Here is a working jsFiddle with a predefined string, for examples sake 强>
答案 2 :(得分: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
}
答案 3 :(得分: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, " "));
}
来自here
所以在你的情况下它应该是这样的:
if (getParameterByName('search_housing').length > 0) { ... }
if (getParameterByName('search_rooms').length > 0) { ... }