我有一个使用 cookie 保持 div 打开的工作示例。部分问题是我使用选择列表而不是单选按钮。另一个问题是选择列表和对应的div的值是动态生成的。然而,让事情变得更容易一些,选择的值总是与 div id 相同。 我只是想这样做,所以如果重新加载页面,div 保持打开状态。 这是我认为与我正在寻找的示例接近的示例:
<fieldset>
<ol class="formset">
<li>
<label for="fname2">First Name: </label>`
<input type="text" id="fname2" value="" name="fname2"/>
</li>
<li>
<label for="lname2">Last Name: </label><br />
<input type="text" id="lname2" value="" name="lname2"/>
</li>
<li>
<label for="email2">Email Address: </label><br />
<input type="text" id="email2" value="" name="email2" />
</li>
<li>
<label for="age2">Are you above 21 yrs old?</label><br />
<input type="radio" name="age2" value="Yes" class="aboveage2" /> Yes
<input type="radio" name="age2" value="No" class="aboveage2" /> No
</li>
</ol>
<ol id="parent2" class="formset">
<li>
<strong>Parent/Guardian Information:</strong>
</li>
<li>
<label for="pname2">Parent Name: </label>
<input type="text" id="pname2" value="" name="pname2"/>
</li>
<li>
<label for="contact2">Contact No.: </label><br />
<input type="text" id="contact2" value="" name="contact2"/>
</li>
</ol>
<input type="submit" name="submit" value="Submit" class="submitbtn" />
</fieldset>
<script>
$(document).ready(function(){
$("#parent2").css("display","none");
$(".aboveage2").click(function(){
if ($('input[name=age2]:checked').val() == "No" ) {
$("#parent2").slideDown("fast"); //Slide Down Effect
$.cookie('showTop', 'expanded'); //Add cookie 'ShowTop'
} else {
$("#parent2").slideUp("fast"); //Slide Up Effect
$.cookie('showTop', 'collapsed'); //Add cookie 'ShowTop'
}
});
var showTop = $.cookie('showTop');
if (showTop == 'expanded') {
$("#parent2").show("fast");
$('input[name=age2]:checked');
} else {
$("#parent2").hide("fast");
$('input[name=age2]:checked');
}
});
</script>
作为注释,我使用的是此处找到的 cookie 插件:http: //plugins.jquery.com/project/Cookie更接近我在做什么和需要帮助的内容如下:
<html>
<head>
<script>
$(document).ready(function() {
$('div.book').css("display","none"); // display none on all ol that doesn't have book class
$('#book_list').change(function() {
$('div.book').slideUp("fast"); //Slide Up Effect
$('#' + $(this).val()).slideDown("slow"); //Slide Down Effect
});
});
</script>
</head>
<body>
<form>
<select id="book_list">
<option value="">Select</option>
<option value="1">Number 1</option>
<option value="2">Number 2</option>
<option value="3">Number 3</option>
</select>
</form>
<div id="1" class="book">Div number 1</div>
<div id="2" class="book">Div number 2</div>
<div id="3" class="book">Div number 3</div>
</body>
</html>
我从数据库中提取值。这是我在重新加载时使用的 PHP 来保持选中菜单项:
<?php
$bookcookie = $_COOKIE['book'];
$book_list = "<select id=\"book_list\">";
while($book = mysql_fetch_array($book_result)){
//THE BOOK LIST
$book_list .= "<option value=\"" . $book['id'] . "\"";
if(isset($bookcookie) && $bookcookie == $book['id']){
$book_list .= " selected";
}
$book_list .= ">Number " . $book['id'] . "</option>";
}
$book_list .= "</select>";
?>