2014-01-23 57 views
1

對不起,對於奇怪的標題,但我不知道任何其他方式來形容它(歡迎改進!)。彈出div顯示兩次點擊後,而不是一個

我正在嘗試製作投資組合網格。當您點擊其中一個圖像時,會在其下方顯示一個框,顯示有關該項目的一些信息。我走得很遠,但碰到一些奇怪的行爲。

我的HTML看起來像這樣:

<ul class="pfGrid"> 
    <li> 
     <a href="./"> 
      <img src="image.jpg" /> 
     </a> 
    </li> 
    ... 
</ul> 

而且我已經想出這個jQuery腳本到滑動並滑出信息框:

<script> 
$(document).ready(function() { 
    $(".pfGrid li a").on("click", function(e) { 
     // no default action when the link is clicked 
     e.preventDefault(); 

     // hide any infobox that is visible 
     $(".pfInfo").slideUp("normal", function() { $(".pfInfo").remove(); }); 

     // if the image isn't allready active 
     if(!$(this).hasClass("pfActive")) { 
      // remove the active class from the previous active item 
      $(".pfGrid li a").removeClass("pfActive"); 

      // add the info box, but hide it 
      $(this).parent().append('<div style=\"display:none;\" class=\"pfInfo\">blaa<br /><br />bla<br />bla</div>'); 
      // slide down the infobox 
      $(".pfInfo").slideDown(); 
      // make the image active 
      $(this).addClass("pfActive"); 
     } 
     // if the image is active, remove the class (info box is already hidden) 
     else { 
      $(".pfGrid li a").removeClass("pfActive"); 
     } 
    }); 
}); 
</script> 

的問題是:當我加載頁面並點擊第一張圖片,信息框顯示出來。當我然後點擊第二個圖像時,框顯示,但也立即隱藏。再次點擊它顯示。然後單擊第三個圖像,信息框顯示,第二次後,等等......

經過一些調試後,我發現問題在於$(".pfInfo").slideUp("normal", function() { $(".pfInfo").remove(); });。我已經用if-else等嘗試過其他的構造,但還沒有得到答案。

另請檢查此JSFiddle

回答

2

在這裏你去

$(document).ready(function() { 
    $(".pfGrid li a").on("click", function(e) { 
     e.preventDefault(); 

     // the problem seems to be in this line: 
     $(".pfInfo").slideUp("normal", function() { $(this).remove(); }); 
     //partially correct - when the slideUp animation, your previous function used to 
     // also remove the newly created .pfInfo element - hence the $(this) replacement 

     if(!$(this).hasClass("pfActive")) { 
      $(".pfGrid li a").removeClass("pfActive"); 

      $(this).parent().append('<div style=\"display:none;\" class=\"pfInfo\">blaa<br /><br />bla<br />bla</div>'); 
      $(this).next().slideDown(); 
       //second change, again the $('.pfInfo') was replaced with .next() 
      $(this).addClass("pfActive"); 
     } 
     else { 
      $(".pfGrid li a").removeClass("pfActive"); 
     } 
    }); 
}); 

希望這會帶來一些輕你的事

PS

小提琴JS是要走的路:d

+1

有時答案可以這麼該死簡單。非常感謝你。 – LinkinTED

相關問題