【发布时间】:2018-03-19 21:07:27
【问题描述】:
有点 js/jquery 新手 - 我正在使用 Bootstrap 和 data-toggle + collapse 类来显示/隐藏 div。我一直在搜索网络,试图找到能够在页面刷新之间保持所有 div 状态的东西,无论是由唯一 ID 还是 CLASS 标识。我看过关于 cookie 和本地存储的讨论,我认为我不在乎使用哪种方法(尽管我遇到过 $.cookie is not a function 的错误,所以本地存储可能更好?)。
问题在于大多数示例都涉及维护手风琴状态,我认为这并不完全适用于此。我尝试过修改各种代码示例,但它们似乎不太奏效。
这是我的代码示例:
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" />
<div class="panel panel-danger">
<div data-toggle="collapse" href="#duesoon" style="cursor: pointer;" class="panel-heading">
<font class="panel-title"><span class='glyphicon glyphicon-fire'></span> Top 5 Expiring Tasks</font>
</div>
<div id="duesoon" class="collapse">
<table class="table table-hover table-striped table-condensed">
<thead>
<tr>
<th class='col-md-7'>Name</th>
<th class='col-md-5'>End Date</th>
</tr>
</thead>
<tbody>
<tr style="cursor: pointer;" onclick="document.location = '?action=view&type=project&id=2">
<td><span class='glyphicon glyphicon-triangle-right'></span> Take Out The Trash</td>
<td>Yesterday</td>
</tr>
</tbody>
</table>
</div>
<div data-toggle="collapse" href="#urgency" style="cursor: pointer;" class="panel-heading">
<font class="panel-title"><span class='glyphicon glyphicon-fire'></span> Top 5 Urgent Tasks</font>
</div>
<div id="urgency" class="collapse">
<table class="table table-hover table-striped table-condensed">
<thead>
<tr>
<th class='col-md-7'>Name</th>
<th class='col-md-5'>Priority</th>
</tr>
</thead>
<tbody>
<tr style="cursor: pointer;" onclick="document.location = '?action=view&type=project&id=1">
<td><span class='glyphicon glyphicon-triangle-right'></span> Save the Whales</td>
<td>Critical</td>
</tr>
</tbody>
</table>
</div>
</div>
如您所见,有一个链接或按钮或切换显示/隐藏 div 的东西。
JSFiddle 上的相同:http://jsfiddle.net/w8psgvaa/2/
我找到了这个代码示例;
$('.collapse').on('hidden', function() {
// store this.id
}).on('shown', function() {
// delete this.id
});
$(document).ready(function(){
$(".collapse").collapse().each(function(){
if( isStored( this.id ) ) {
$( this ).collapse( 'hide' );
}
});
});
但不幸的是,它并不完整。并且一些 div 开始折叠(如在我的示例中)。任何帮助表示赞赏!
【问题讨论】:
-
您收到 cookie 错误,因为您没有包含它的 js 库 --- github.com/carhartl/jquery-cookie 或 github.com/js-cookie/js-cookie
-
您好 Tasos,是的,它没有包含在上面的示例中,但是我在尝试一些 cookie 代码示例时已经包含了它,但我仍然收到该错误。也许这是与其他东西的冲突或我使用的代码的问题。谢谢!
-
感谢谦虚,我会对此进行更多研究,看看是否可以将其应用于我想要完成的工作。我更喜欢后端人员 (PHP) - 但我需要了解更多关于前端编码的知识。
标签: javascript jquery css twitter-bootstrap