更改多个元素的切换状态,并在页面刷新时需要保留在localstorage

时间:2017-04-02 20:04:32

标签: javascript jquery html5 twitter-bootstrap local-storage

当单击放置在该面板上的按钮时,有多个可折叠面板和特定面板折叠。单击该按钮时,该按钮切换为加号和减号图标。拼接面板和按钮图标应保持相同状态页面刷新。面板部件工作正常,但切换按钮不会保持相同的状态,即加号图标在点击时切换为减号图标,但再次点击时,它仍然只是减号图标,而不是更改回加号图标。我使用localstorage来保存面板和按钮的状态。但我错过了某个地方按钮的正确方法。我是jquery的新手,并尝试了在这里和其他平台上给出的所有答案,但无法弄清楚确切的问题。请帮助指出出了什么问题。如果需要任何其他信息,请告诉我。

<div class="row">
<div class="col-md-8 col-sm-6 col-xs-12">
<div class="panel panel-primary">
<div class="panel panel-heading" style="height: 45px;">
<h4 class="text-center" ><span class="glyphicon glyphicon-film" aria-hidden="true" style="padding-right: 10px;"></span>Name
<span data-toggle="collapse" data-target="#{{ template }}">
<span class="more-less pull-right" aria-hidden="true" id="{{ icon }}" ><i class="glyphicon glyphicon-plus-sign"></i></span>
</span>
</h4>
</div>
<div class="panel-collapse collapse" id="{{ template }}">
<div class="panel-body">
<div class="row">
<div class="col-md-4 col-sm-6 col-xs-12"><p class="lead"><b>Duration : </b> 1 Hour</p></div>
<div class="col-md-1 col-sm-6 col-xs-12"></div>
<div class="col-md-4 col-sm-6 col-xs-12"><h4 class="text-muted "><code>Module Topics</code></h4></div>
<div class="col-md-1 col-sm-6 col-xs-12"></div>
<div class="col-md-2 col-sm-6 col-xs-12">
</div>
</div>

Jquery的:

    $(".more-less").click(function ()
    {
        $(this).find('i').toggleClass('glyphicon-plus-sign').toggleClass('glyphicon-minus-sign');
        var active = $(this).attr('id');
        var activeclass = $(this).find('i').attr('class');
        var gicon= localStorage.gicon === undefined ? new Array() : JSON.parse(localStorage.gicon);
        if ($.inArray(active,gicon)==-1) //check that the element is not in the array
            gicon.push(active);
            gicon.push(activeclass);
        localStorage.gicon=JSON.stringify(gicon);
    });


    $(document).ready(function() {
    var gicon=localStorage.gicon === undefined ? new Array() : JSON.parse(localStorage.gicon); 
        for (var i in gicon){ 
            if ($("#"+gicon[i]).find('i').hasClass('glyphicon-plus-sign'))
            {
                $("#"+gicon[i]).html('<i  class="glyphicon glyphicon-minus-sign"></i>');

            }
        }
    });

1 个答案:

答案 0 :(得分:2)

这是工作示例https://jsfiddle.net/sL2tmrsd/ - 用它来测试。 我重构了你的代码。

请注意,永远不要使用new Array()使用[]

Stackoverflow的代码片段无法与localStorage一起使用,因此请勿点击“运行代码段”。

   $(document).ready(function() {

		
		function expandPanelOnInit() {
			var activePanel = localStorage.getItem('activePanel');
			
			// We exit function if activePanel is not set yet
			if (activePanel === null) {
				return;
			}

			$('a[aria-controls="' + activePanel + '"]')
				.removeClass('collapsed')
				.attr('aria-expanded', true)
				.find('i').toggleClass('glyphicon-plus-sign glyphicon-minus-sign');
				
			$('#' + activePanel).addClass('in');
			
			
		}
		
		expandPanelOnInit();
        
        $('a[role="button"]').click(function() {
          var id = $(this).attr('aria-controls');
		  var _thisIcon = $(this).find('i');
		  
		  localStorage.setItem('activePanel', id);
		  
		  
		  
		  $('#accordion i.glyphicon').not(_thisIcon)
			.removeClass('glyphicon-minus-sign')
			.addClass('glyphicon-plus-sign');
		  
		  _thisIcon.toggleClass('glyphicon-plus-sign glyphicon-minus-sign');
          
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>


<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingOne">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" aria-controls="collapseOne">
          <i class="glyphicon glyphicon-plus-sign"></i>
        </a>
      </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingTwo">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
          <i class="glyphicon glyphicon-plus-sign"></i>
        </a>
      </h4>
    </div>
    <div id="collapseTwo" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
  <div class="panel panel-default">
    <div class="panel-heading" role="tab" id="headingThree">
      <h4 class="panel-title">
        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
          <i class="glyphicon glyphicon-plus-sign"></i>
        </a>
      </h4>
    </div>
    <div id="collapseThree" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingThree">
      <div class="panel-body">
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute, non cupidatat skateboard dolor brunch. Food truck quinoa nesciunt laborum eiusmod. Brunch 3 wolf moon tempor, sunt aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft beer labore wes anderson cred nesciunt sapiente ea proident. Ad vegan excepteur butcher vice lomo. Leggings occaecat craft beer farm-to-table, raw denim aesthetic synth nesciunt you probably haven't heard of them accusamus labore sustainable VHS.
      </div>
    </div>
  </div>
</div>