2011-02-12 73 views
0

我使用下面的JavaScript(jQuery)来切换打开两个DIV。 DIV一次打开并打开一个,这就是我所追求的。不过,我也希望DIV在第二次点击时关闭,尽管我尽了最大的努力,但这并未发生!jQuery切换修改

的Javascript:

$(document).ready(function() { 
    $('.info_tab').click(function() { 
     var currentID = $(this).next().attr("id"); 
     $('.toggle_info[id!=currentID]').hide(); /* the intention here is to hide anything that is not the current toggling DIV so as to close them as a new one is opened. I thought this would leave the currently selected DIV uninterrupted to toggle closed (below), but it doesn't */ 
     $(this).next().toggle(); 
     return false; 
     }); 
    }); 

HTML:

 <div class="info_tab"> 
      <h1>Person One</h1><br /> 
      <p>click for less info</p> 
     </div> 
     <div id="person_one_info" class="toggle_info"> 
      <p>More information about Philip Grover</p> 
     </div> 
     <div class="info_tab"> 
      <h1>Person Two</h1><br /> 
      <p>click for less info</p> 
     </div> 
     <div id="person_two_info class="toggle_info"> 
      <p>More information about Roy Lewis</p> 
     </div> 

如果需要任何更多的信息,就问我,我会很乐意编辑的问题。

干杯,

丰富

回答

2

你有这个概念了,但不使用 “currentID” 正确。你需要记住它是一个变量,如果你想对它进行评估,则不能在另一个字符串中。

随着中说,试试这个:

$('.toggle_info[id!='+currentID+']').hide(); 

这使得在选择的变量得到评估,然后将它关到了jQuery找出。

它看起来像你要去一个手风琴效果。和jQuery UI有just such a control,你可以使用(如果你感兴趣)。如果你正在寻找经验,那么继续。 ;-)

+0

完美的作品!我只是在寻找经验 - 我最后的喘息是使用jQuery的手风琴,但我确信我可以自己做!非常感谢:) – RichieAHB 2011-02-12 18:32:08