2013-05-29 80 views
0

嘿所以我試圖爲點擊事件創建自定義切換jQuery函數。基於DIV ID的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盒子上時,原來可見的盒子將會變得不可見,新的可見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// 
     }); 

你能幫我嗎?

+0

是'$( 'span_2> DIV。') 「對嗎?」 'span_2' divs中沒有後代div – jammykam

+0

它只是一段代碼,所以它確實有後代。我只是沒有包括他們,因爲他們與我正在嘗試做的事無關。 – OntheRise

回答

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'); 
}); 
+0

是的,工作。我肯定採取了艱難的方式圍繞這個哈哈。感謝您的洞察! – OntheRise

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(); 
});