簡體   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>

我試圖通過將 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;
}

您可以從 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM