2017-03-12 51 views
0

我試圖找到一種方法來簡化此腳本,以便它不需要硬編碼的散列名稱。所以如果你添加一個帶有mytest的新鏈接和一個ID爲mytest的div,它就可以工作,而不必訪問腳本並將mytest添加到腳本中。希望我明確提出我的問題。簡化JS,以便不需要在腳本中硬編碼散列

我非常友好的感謝任何幫助瞭解這一點。

  jQuery(function($) { 
       $('#menu-bottomnav li a').click(function(e) { 
       e.preventDefault(); 
       animateSlider(this.hash); 
       }); 

       function animateSlider(hash) { 
       if (!$('#popups div.open').length) { 
        if (hash == '#bio') { 
        openPopup(hash); 
        } 
        if (hash == '#resume') { 
        openPopup(hash); 
        } 
       } else { 
        if (hash == '#bio') { 
        openAndClose(hash) 
        } 
        if (hash == '#resume') { 
        openAndClose(hash) 
        } 
       } 
       } 


       function openPopup(hash) { 
       $(hash).slideToggle().addClass('open'); 
       } 


       function openAndClose(hash) { 
       if ($(hash).hasClass('open')) { 
        $($(hash)).slideToggle().removeClass('open'); 
       } else { 
        $('#popups div.open').slideToggle().removeClass('open'); 
        $(hash).slideToggle().addClass('open'); 
       } 
       } 
      }); 

已經在這裏工作的例子https://jsfiddle.net/a4y7z2fm/

回答

1

怎麼是這樣的:

jQuery(function($) { 
    $('#menu-bottomnav li a').click(function(e) { 
    e.preventDefault(); 
    animateSlider(this.hash); 
    }); 

    function animateSlider(hash) { 
    $('.open').slideToggle().removeClass('open'); 
    $(hash).slideToggle().addClass('open'); 
    } 
}); 
+0

好於我的回答;) – quack

+0

嘿,謝謝! :) - 男人,我繼續使用這個網站像它的reddit。 – hola

+0

完美無瑕,正是我期待的! –

0

也許我不明白的問題,但現在看來似乎會工作,如果只是罰款你只是通過了散列變量而沒有if語句:

jQuery(function($) { 
$('#menu-bottomnav li a').click(function(e) { 
    e.preventDefault(); 
    animateSlider(this.hash); 
}); 

function animateSlider(hash) { 
    if (!$('#popups div.open').length) { 
     openPopup(hash); 
    } else { 
     openAndClose(hash); 
    } 
} 


function openPopup(hash) { 
    $(hash).slideToggle().addClass('open'); 
} 


function openAndClose(hash) { 
    if ($(hash).hasClass('open')) { 
     $($(hash)).slideToggle().removeClass('open'); 
    } else { 
     $('#popups div.open').slideToggle().removeClass('open'); 
     $(hash).slideToggle().addClass('open'); 
    } 
    } 
}); 
+0

輝煌我已經這麼多小時了,我忽略了簡單的回答庸醫的想法。但我必須把它交給你,你真的想要簡化我可怕的代碼。我不是最好的我主要知道如何做一個功能混亂謝謝你們倆! –