2017-04-17 54 views
0

基本上我有至少20個或更多按鈕和textareas像這些不同的類名稱。如何將DRY方法應用於多個jQuery按鈕切換

<textarea class="widefat res_editor_exp2wid1" rows="10" cols="20" style="display: none;" id="<?php echo $this->get_field_id('jd1'); ?>" name="<?php echo $this->get_field_name('jd1'); ?>"><?php echo esc_attr($instance['jd1']); ?></textarea> 
<button class="res_editor_btn_exp2wid1" type="button">Edit Content</button> 

我在做什麼是點擊按鈕後擴大textarea的。通過做 -

jQuery(document).on('click', '.res_editor_btn_exp2wid1', function(){ 

    jQuery(".res_editor_exp2wid1").toggle("slow").click(function(){ 
     jQuery('.res_editor_exp2wid1').trumbowyg(); 
    }); 
}); 

每次我必須寫這個jQuery這有點煩人,我想使它成爲一個乾的方法。我如何才能做到這一點?對不起如果這聽起來很荒謬,我在這件事上很新手。任何幫助,將不勝感激。

回答

0

1)你可以做一個each循環,而不是循環遍歷每個div,然後找到div中的每個元素來執行你的功能。例如:

假設HTML是沿着線:

<div class="foo"> 
    <button class="btn">Button</button> 
    <div class="expand_me">...</div> 
</div> 

那麼你的JS是

jQuery('.foo').each(function() { 
    $button = $(this).find('button'); 
    $div = $(this).find('.expand_me'); 
    // do something to the button + div 
}); 

2)您可以創建一個你要求每個20對事物的功能需要有這種行爲:

var clickable = function(unique_code) { 
    jQuery(document).on('click', '.res_editor_btn_'+unique_code, function(){ 
    jQuery(".res_editor_"+unique_code).toggle("slow").click(function(){ 
     jQuery('.res_editor_'+unique_code).trumbowyg(); 
    }); 
    }); 
}; 

然後對於每20次你需要這樣做:

clickable('exp2wid1'); 
+1

感謝您的評論,我會盡力實現這一點,並與您取得聯繫 –