カスタムデータ属性「data-*」を使って要素の表示非表示を制御する

色々な要素を表示、非表示する関数を作ったので公開

CSS

  1. function hideAndShow(op){
  2. var target = 'target', // 対象のグループ名
  3. show = 'show', // 対象の名前
  4. group = 'group', // 被対象のグループ名
  5. name = 'name', // 被対象の名前
  6. active = 'is-active', // アクティブクラス
  7. inactive = 'is-inactive'; // 非アクティブクラス
  8. // 対象グループを非表示
  9. function toHide(tag){
  10. $('[data-'+group+'*="'+tag+'"]').hide();
  11. }
  12. // 対象グループの対象ネームを表示
  13. function toShow(g,t){
  14. $('[data-'+group+'*="'+g+'"][data-'+name+'*="'+t+'"]').show();
  15. }
  16. // クラスを変更
  17. function changeClass(e,g){
  18. $('[data-'+target+'*="'+g+'"]').not(e).removeClass(active).addClass(inactive);
  19. $(e).removeClass(inactive).addClass(active);
  20. }
  21. // 実行内容
  22. function allPractice(e){
  23. var d = e.currentTarget.dataset,
  24. splitTarget = d[target].split(','),
  25. splitShow = d[show].split(',');
  26. $.each(splitTarget,function(i,group){
  27. toHide(group);
  28. $.each(splitShow,function(j,name){
  29. toShow(group,name);
  30. if(op.addClass !== void 0 && $.inArray(group,op.addClass) >= 0)changeClass(e.target,group);
  31. });
  32. });
  33. }
  34. // 対象の設定されたタグをクリックで実行
  35. $('[data-'+target+']').on('click',allPractice);
  36. // 全てのグループを非表示
  37. $('[data-'+group+']').hide();
  38. // 初期表示
  39. if(op.defaultShow !== void 0){
  40. $.each(op.defaultShow,function(i,v){
  41. toShow(v.group,v.name);
  42. });
  43. }
  44. }
  45. $(function(){
  46. hideAndShow({
  47. addClass : ['test'], // 起動する要素のクラスを変更するグループ名
  48. defaultShow : [{ // 初期表示
  49. group : 'test', // グループ名
  50. name : 'tag1' // 名前
  51. }]
  52. });
  53. });

実際に動かしてみる

test-tag1
test-tag2
test-tag3