简体   繁体   English

将 onload 函数与 call 函数合并

[英]Merging onload function with call function

 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>

I'm attempting to reduce lines of code by merging onload function with called function.我试图通过将 onload 函数与被调用函数合并来减少代码行。

So the goal is to merge this lines of code:所以目标是合并这行代码:

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

With this line of code:使用这行代码:

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

You could call opaFilterToggle from your onload function, and add a parameter to turn off functionality when calling from onload.您可以从 onload 函数调用opaFilterToggle ,并添加一个参数以在从 onload 调用时关闭功能。 If your goal is to reduce lines the opaFilterToggle can be shortened up a bit.如果您的目标是减少线条,则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));
  }
}

Be sure to update the html to include the additional parameter.请务必更新 html 以包含附加参数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM