0
問題描述
我希望我的網站在單擊我的元素時顯示圖。擺脫jQuery代碼冗餘,僅與參數不同
問題是 - 我有4個地方和3個間隔。那是4 * 3 = 12個地塊:
var places = ['place1','place2','place3','place4']
var interval = [1,2,3]
每間隔我有陣列的一個單獨的陣列,其保持樣品每個地方分別
samples1[]
samples2[]
samples3[]
samples1[0]
裝置「的interval=1
樣本列表place1
「
samples1[1]
裝置 」爲place2
「 等interval=1
樣本列表..
情節本身看起來是這樣的:
<div id="plot-place1">
<div class = interval-button id = "interval1">interval1</div>
<div class = interval-button id = "interval2">interval2</div>
<div class = interval-button id = "interval3">interval3</div>
<div id = "place1"><!-- Plotly chart will be drawn inside this DIV --></div>
</div>
功能,顯示默認打印了指定的地方是這樣的:
/* Shows plot's container (div) for place1, interval=1 */
$(document).ready(function(){
$(this).on('click', '.place1', function(){
$('#plot-place1').fadeToggle('fast');
showPlot(samples1[0], 'place1');
});
});
然後,我有一個功能,點擊間隔按鈕後,改變了單一的情節在具體規定的時間間隔:
$(document).ready(function(){
$('#plot-place1').on('click', '#interval2', function(){
showPlot(samples1[3], 'sypialnia');
});
});
所以對12個地塊我有12個相同的功能,即改變情節的間隔只有用不同的申辯發言:。 我也有4個幾乎相同的功能來顯示指定地點的情節。
這個看起來毛茸茸的!我想擺脫冗餘,但我是新來的jQuery,我知道,應該有一些像Java模板函數,但我不知道從哪裏開始。
這個Hypotetical模板將是:
/* shows plot's container (div)*/
$(document).ready(function(){
$(this).on('click', <plot's_place-based_id> , function(){
$(<plot_container_id>).fadeToggle('fast');
showPlot(<array_of_samples>, <place>);
});
});
/* shows specified plot */
$(document).ready(function(){
$(<plot_container_id>).on('click', <interval_button_id>, function(){
showPlot(<array_of_samples>, <place>);
});
});
問題
如何擺脫冗餘的?
明白這個問題是否清楚?
我是怎麼擰的?
可以設置plot_container_id作爲數據屬性在元素中,您將事件附加到事件目標元素並獲取它。 – Martin