简体   繁体   中英

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.

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. If your goal is to reduce lines the opaFilterToggle can be shortened up a bit.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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