0

クリック イベント用のカスタム トグル jQuery 関数を作成しようとしています。

HTML は次のように構成されています。

//These are the clickable boxes, CSS is taking care of the div's as squares//
<div class="span_2" data-col-name="hid_1">1</div>
<div class="span_2" data-col-name="hid_2">2</div>
<div class="span_2" data-col-name="hid_3">3</div>

//Hidden div's (through class style display:none;) boxes that correspond to the clickable boxes above//
<div class="toggle_col" id="hid_1">Hi</div>
<div class="toggle_col" id="hid_2">Mello</div>
<div class="toggle_col" id="hid_3">Rock</div>

//jQuery to make hidden div boxes toggle
$('.span_2 > div').click(function () {

           var $colToShow = $(this).attr('data-col-name');
           $('#' + $colToShow).toggleClass('toggle_col');
       });

これはすべて機能します。非表示のボックスは、対応する div ボックスがクリックされてクラスが削除されると、表示が切り替わります。しかし、私が追加したいのは、クリック可能な div ボックスの別の 1 つでクリック イベントが発生すると、表示された元のボックスが再び非表示になり、新しい表示 div がそのスペースを取ることです。これは私がやろうとしたことです:

//jQuery adapted from the code before//
$('.span_2 > div').click(function () {
           var group = $('div[id^="hid"]'); //Create an array of hidden div boxes using the id//
           if(i=0;i<group.length;i++){ //Progress through each div and check to see if it's not hidden by the class//
              if(!group[i].hasClass('toggle_col')){ //It if isn't hidden make it hidden by toggling class//
                  group[i].toggleClass('toggle_col');
              }
           }


           var $colToShow = $(this).attr('data-col-name'); 
           $('#' + $colToShow).toggleClass('toggle_col');//Now make corresponding hidden div based on clickable box div appear//
       });

手伝って頂けますか?

4

2 に答える 2

0

最初にすべての div を非表示にしてから、対応するクリックされた div を表示しないのはなぜですか? クラスを切り替えるのではなく、show()メソッドを使用して非表示の div を表示します。

//These are the clickable boxes, CSS is taking care of the div's as squares//
<div class="span_2" data-col-name="hid_1">1</div>
<div class="span_2" data-col-name="hid_2">2</div>
<div class="span_2" data-col-name="hid_3">3</div>

//Hidden div's (through class style display:none;) boxes that correspond to the clickable boxes above//
<div class="toggle_col" id="hid_1">Hi</div>
<div class="toggle_col" id="hid_2">Mello</div>
<div class="toggle_col" id="hid_3">Rock</div>

//jQuery to make hidden div boxes toggle
$('.span_2 > div').click(function () {

    $('.toggle_col').hide();
    var $colToShow = $(this).attr('data-col-name');
    $('#' + $colToShow).show();
});
于 2013-05-29T04:06:33.310 に答える
0

あなたの近くに...これを試してみてください..

$('.span_2 > div').click(function () {
           // add the toggle_col class to all of the elements with 
           // an id starting with hid_ if they have a common parent then you can
           // add that as part of the selector to scope the behavior a little better

           $('div[id^=hid_]').addClass('toggle_col');
           var $colToShow = $(this).attr('data-col-name');
           $('#' + $colToShow).toggleClass('toggle_col');
});
于 2013-05-29T04:07:02.467 に答える