来自使用JSON字符串的数据属性的jQuery cookie

时间:2014-04-02 12:30:25

标签: jquery json cookies twitter-bootstrap-3 toggle

我有一系列使用Bootstrap切换jQuery切换的div。我需要创建一个记住并保留div的切换状态的cookie。我尝试将切换状态设置为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 &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

非常有必要获得任何见解。

1 个答案:

答案 0 :(得分:0)

您需要将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: '/'});
}