2017-04-17 9 views
0

基本的には、クラス名が異なるこれらのボタンとテキストエリアが少なくとも20個以上あります。複数のjQueryボタントグルでDRYアプローチを適用する方法

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

私がやっていることは、ボタンをクリックしてテキストエリアを拡大することです。これにより -

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

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

たびに、私はちょっと面倒です。このjQueryのを記述する必要があり、私はそれDRYアプローチしたいです。私はそれをどのように達成できますか?申し訳ありませんがばかげて聞こえる場合、私はこの問題ではかなり初心者です。どんな助けもありがとう。

答えて

0

1)各divをループした後、div内の各要素を見つけて機能を実行する代わりに、eachループを実行できます。例えば:

と仮定すると、HTMLの線に沿っている。そして、あなたのJSが

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

2)あなたが20物事ごとに呼び出す関数を作成することができますでしょう

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

こと

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

コメントをいただきありがとうございます、私はこれを実装して、あなたに連絡します –

関連する問題