【发布时间】:2014-04-02 12:30:24
【问题描述】:
我有一系列用 Bootstrap 的切换 jQuery 切换的 div。我需要创建一个 cookie 来记住并保留 div 的切换状态。我正在尝试将切换状态设置为 json 字符串(由 here 推荐),以便只有一个 cookie。
我遇到了一个似乎无法通过的障碍。 json 数组正在创建中,但它总是落后一个,可以这么说。
jQuery:
$('#style-widget [data-toggle="collapse"]').on('click', function() {
var check_open_divs = [];
var toggled_div = $('#style-widget [data-toggle="collapse"]:not(.collapsed)');
// PROBLEM BELOW ▼ -- on initial click the data attribute is not going into the array
// on second click (when the class 'toggled' is being added by Bootstrap code) the
// data attribute is added to the array
$(toggled_div).each(function() {
check_open_divs.push($(this).attr('data-target'));
});
// stringify array object
check_open_divs = JSON.stringify(check_open_divs);
$.cookie('bg-noise-div-state', check_open_divs, {expires:365, path: '/'});
});
(简化的)HTML:
<div id="style-widget">
<!-- div one -->
<p title="click to toggle" class="collapsed" data-toggle="collapse" data-target="#background-noise-wrap">Background Noise</p>
<div id="background-noise-wrap" class="collapse">
<!-- content here, removed for brevity -->
</div>
<!-- div two -->
<p title="click to toggle" class="collapsed" data-toggle="collapse" data-target="#extra-header-selection-wrap">Extra Header</p>
<div id="extra-header-selection-wrap" class="collapse">
<div class="selection-wrap first">
<!-- content here, removed for brevity -->
</div>
</div>
<!-- div three -->
<p title="click to toggle" class="collapsed" data-toggle="collapse" data-target="#wide-or-boxed-wrap">Wide or Boxed?</p>
<div id="wide-or-boxed-wrap" class="collapse">
<p>Header & Footer</p>
<div id="wide-boxed-selection-wrap">
<!-- content here, removed for brevity -->
</div>
</div>
</div>
默认情况下,div 是折叠的,这就是它们最初具有 .collapsed 类的原因。在伪代码思维中:
1. create function on click of collapse toggle (the p tag)
2. select divs that are not collapsed
3. save these to a json string, then cookie
4. check for this cookie on page load to persist the toggled states
非常感谢任何见解。
【问题讨论】:
-
我不确定您所说的 json 落后是什么意思。我对其进行了测试并且它正在工作(尽管我必须从 click 事件中删除
#style-widget以使其正常工作),但是没有任何内容进入 json 字符串,因为它选择的元素都具有.collapsed类。此外,请确保以;结束 javascript 行。您在var toggled_div和$.cookie()上缺少那些。你能更具体地解释一下问题是什么吗? -
更新了问题以更好地解释。添加了
#style-widgetdiv,这是我之前从插图代码中忘记的。还解释了拥有.collapsed类并通过选择删除了 `.collapsed' 类的那些来检查切换 div 的逻辑(这似乎是问题所在)。 -
所以,如果我理解正确,您是说问题是当您切换 div 时,在您再次单击它之前,它无法正确反映在 json 字符串中?
-
正确。在第一次切换
console.log(check_open_divs);时,只需返回[],在第二次切换相同或不同的 div 时,将数据属性输入到 json 字符串中。
标签: jquery json cookies twitter-bootstrap-3 toggle