将onload函数与调用函数合并

时间:2016-05-05 20:41:46

标签: javascript

var localStorageKey = 'togglestate';

var savedState = localStorage.getItem('togglestate');

var defaultState = { 'open':true };

var state = savedState ? JSON.parse(savedState) : defaultState;

jQuery(function($) {
  if(state['open']) {
    jQuery('.accordion-header').addClass('open');
  } else {
    jQuery('.accordion-header').removeClass('open');
  }
  
});

function opaFilterToggle(elem) {
  if(state['open']) {
    jQuery(elem).addClass('open');
    state['open'] = false;
  } else {
    jQuery(elem).removeClass('open');
    state['open'] = true;
  }
  
  localStorage.setItem(localStorageKey, JSON.stringify(state));
}
.accordiong-header {
  height:0;
}
.accordiong-header.open {
  height:auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="accordion-header">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
</div><br/><br/>
<a href="#" onclick="opaFilterToggle('.accordion-header')">Click Me</a>

我试图通过将onload函数与被调用函数合并来减少代码行。

所以我们的目标是合并这行代码:

if(state['open']) {
  jQuery('.accordion-header').addClass('open');
} else {
  jQuery('.accordion-header').removeClass('open');
}

使用以下代码:

if(state['open']) {
  jQuery(elem).addClass('open');
  state['open'] = false;
} else {
  jQuery(elem).removeClass('open');
  state['open'] = true;
}

随机文本绕过stackoverflow的文本最低要求: Lorem Ipsum只是印刷和排版行业的虚拟文本。自16世纪以来,Lorem Ipsum一直是业界标准的虚拟文本,当时一台未知的打印机采用了类型的厨房,并将其拼凑成一本类型的样本。它不仅存在了五个世纪,而且还延续了电子排版,基本保持不变。它在20世纪60年代随着包含Lorem Ipsum段落的Letraset表格的推出而普及,最近还推出了包括Lorem Ipsum版本在内的桌面出版软件Aldus PageMaker

1 个答案:

答案 0 :(得分:0)

您可以从onload函数调用opaFilterToggle,并添加一个参数以在从onload调用时关闭功能。如果您的目标是减少行数,opaFilterToggle可以缩短一点。

jQuery(function($) {
  opaFilterToggle('.accordion-header', false);
});

function opaFilterToggle(elem, changeState) {
  state['open'] ? jQuery(elem).addClass('open') : jQuery(elem).removeClass('elem');

  if(changeState) {
     state['open'] = !state['open'];
     localStorage.setItem(localStorageKey, JSON.stringify(state));
  }
}

请务必更新html以包含其他参数。

<a href="#" onclick="opaFilterToggle('.accordion-header', true)">Click Me</a>