2013-10-18 100 views
5

我已經能夠讓我的div s打開並更改圖像,但我想要發生的是當我打開另一個關閉時,我不確定如何去做這件事。想打開另一個div時關閉div

我有多個div是這樣的。每個id新聞是自己獨立的名字:

<div class="article" id="news"> 
    <h2>Hot News: Board Votes to Improve Highways</h2> 
    <p>As Sporktown’s native and tourist population has increased, so has traffic. The good news is we are taking steps to deal with it. Before traffic becomes too much of a problem we have a plan to expand current highways and improve current ones.</p> 
    <div class="moreText"> 
     <p> 
      As part of the new plan, Route 7 will be expanded from a two-way highway to a four-lane highway. This will dramatically speed up North–South travel through that corridor. 
     </p> 
     <p> 
      In addition to the road widening on Route 7, we have finally received approval to for the extension. The original plan called for Route to continue farther North. The project is finally cleared and work has already begun. 
     </p> 
    </div> 
    <img src="img/more-button.png" width="51" height="16" class="changeTextButton">  
</div> 

這裏是jQuery腳本我有這麼遠:

$(document).ready(function() 
{ 
    $('.changeTextButton').click(function() 
    { 
     $(this).siblings('.moreText').slideToggle(500); 
     if ($(this).attr('src') == 'img/more-button.png') 
     { 
      $(this).attr('src', 'img/less-button.png'); 
     } 
     else 
     { 
      $(this).attr('src', 'img/more-button.png'); 
     } 
    }); 
}); 

回答

2

此行後只要添加

$('.moreText').slideUp(); 

$('.changeTextButton').click(function() { 

這會滑動「.moreText」的所有實例,但當前打開的實例除外。

4

,你可以使用類.articles關閉所有其它的div,然後使用div的各個ID顯示像

$(".articles").hide(); 
$("#news").show(); 

這將隱藏具有DIV有id作爲類articls和顯示所有div新聞

0

以全局變量的分配對象/股利的ID在每個changeTextButton點擊這個變量和獲得prevoius ID的標識和隱藏

聲明全局變量:

window.news;//news is global variable 

隱藏/顯示DIV

$("#"+news).hide(); 
$("#newdiv").show(); 
+0

你並不需要使用一個變量(全局或局部)記住哪個格是開放的。 –

1

試試這個腳本

$(document).ready(function() { 
var $parentid = ""; 

    $('.changeTextButton').click(function() { 

      if($parentid!="" && $parentid!=$(this).parent().attr("id")){ 
       $("#"+$parentid).find(".moreText").slideUp(); 
      } 

     $(this).siblings('.moreText').slideToggle(500); 
     $parentid=$(this).parent().attr("id"); 

     if ($(this).attr('src') == 'img/more-button.png') { 
      $(this).attr('src', 'img/less-button.png'); 
     } 
     else { 
      $(this).attr('src', 'img/more-button.png'); 
     } 

    }); 

});