jQuery cookie from data-attributes using JSON string



我有一系列的div,用Bootstrap的切换jQuery切换。我需要创建一个 cookie 来记住并保留div 的切换状态。我正在尝试将切换状态设置为json字符串(如此处建议的那样),以便只有一个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 &amp; 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

非常需要任何见解。

您需要将 cookie 创建封装到一个函数中,然后在切换类调用该函数。

$('[data-toggle="collapse"]').on('click', function() {
    // toggle your div class here
    $(this).toggleClass('expanded collapsed');
    // call function to store value
    storeState();
 });
function storeState() {
    var check_open_divs = [];
    var toggled_div = $('#style-widget [data-toggle="collapse"]:not(.collapsed)');
    $(toggled_div).each(function() {
      check_open_divs.push($(this).attr('data-target'));
    });
    // stringify array object
    check_open_divs = JSON.stringify(check_open_divs);
    console.log(check_open_divs);
    $.cookie('bg-noise-div-state', check_open_divs, {expires:365, path: '/'});
}

最新更新