传递变量在另一个页面上运行
我正在一个网站上工作,并且正在计划让它在某些链接上设置值,这将改变页面加载时显示的容器。我将如何获得它,以便链接传递将用于onload函数的值?传递变量在另一个页面上运行
这里是我的HTML代码中的样机:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Lunch</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="script.js"></script>
</head>
<body onload="navBar(); dateChange(); tabulate(0);">
<nav>
<ul>
<li><a href="appy.html">Appitizers</a></li>
<li><a href="break.html">Breakfast</a></li>
<li><a href="lunch.html">Lunch</a></li>
<li><a href="dinner.html">Dinner</a></li>
<li><a href="dessert.html">Dessert</a></li>
<li><a href="special.html">Ten-Course Dinner</a></li>
<li><a href="share.html">Send in your Recipes!</a></li>
</ul>
</nav>
<div class="main">
<div class="box">
<ul>
<li><a onclick="tabulate(this.id);" id="1">Chicken Clubhouse Sandwiches</a></li>
<li><a onclick="tabulate(this.id);" id="2">Smokey Tomato Soup</a></li>
</ul>
</div>
<div id="0" class="recipe" style="display: block;">
<div class="tabs">
<a class="tab"> </a>
</div>
<div class="page">
<p>The recipes you'll find here are ones you can use to impress guests at your next get together</p>
</div>
</div> <!--recipe card end-->
<div class="recipe" id="1">
<h1>Chicken Clubhouse Sandwiches</h1>
</div> <!--recipe card end-->
<div class="recipe" id="2">
<h1>Smokey Tomato Soup</h1>
</div> <!--recipe card end-->
</div>
</body>
</html>
,这里是我的制表功能:
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}
您将需要使用的URL的GET
parameters:
lunch.html?item=2
将变量传入JavaScript函数中:
// Set up an object for GET parameter
var $_GET = {};
// Find and extract the various GET parameters
if(document.location.toString().indexOf('?') !== -1) {
var query = document.location.toString().replace(/^.*?\?/, '').replace(/#.*$/, '').split('&');
for(var i=0, l=query.length; i<l; i++) {
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
// Target a specific get parameter, given the GET parameter name
var tabNum = $_GET['item']; // Comes through as '2' in this example
// Pass the parameter into the function
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}
希望这会有所帮助! :)
这帮了很多!但是,我不需要$ _GET部分,我直接将aux [1]分配给tabNum。 –
这取决于您在GET中传递了多少个参数,但是,如果只有一个参数,则该参数将起作用。很高兴听到它帮助你:) –
坏消息,由于某种原因,它不是在托管网站上工作... –
我没有测试过这一点,但你应该能够通过PHP传递GET变量到制表(),在这样的方式来获得的:
function tabulate(tabNum){
$('.recipe').each(function() {
if(tabNum==this.id){
this.style.display="block";
}
else{
this.style.display="none";
}
});
}
window.addEventListener('DOMContentLoaded', function(evt) {
var id = <?php echo htmlspecialchars($_GET['id'], ENT_COMPAT, 'utf8'); ?>;
tabulate(id);
});
我相信,这将工作,但我使用的托管网站不支持PHP –
对不起。我想我假设你有PHP可用。在这种情况下,您可能需要发挥创意。 – hRdCoder
没关系,我应该说我从一开始就没有PHP访问权限 –
只是一个快速的头的了:你拼错了“开胃菜”:) – deckeresq