2014-09-01 75 views
0

我將以下jQuery拼湊在一起以使手風琴效果起作用。該工程...想知道爲什麼這個jQuery不起作用?

$("#FAQs .answer").hide(); 
$("#FAQs .close").hide(); 
$("#FAQs .open").show(); 

// Click the #Expand button to show and hide .answer 
$('#Expand').click(function() { 

if ($(this).text() === 'Minimise FAQs') { 
    $(this).text('Expand FAQs'); 
    $('#FAQs .answer').slideUp('fast'); 
    $("#FAQs .close").hide(); 
    $("#FAQs .open").show(); 

} else { 
    $(this).text('Minimise FAQs'); 
    $('#FAQs .answer').slideDown('fast'); 
    $("#FAQs .close").show(); 
    $("#FAQs .open").hide(); 

} 
}); 

// Click the Quesiton (h2) to show and hide the answer 
$("#FAQs h2").addClass("link").click(function() { 
$(this).parent().children(".answer").slideToggle('fast'); 
$(this).parent('li').children(".close").toggle(); 
$(this).parent('li').children(".open").toggle(); 
}); 

此代碼(以上)作出如下HTML打開和關閉頁上的所有手風琴:

<section class="row m_b_zero"> 
<div class="inner-container"> 
    <div class="box"> 
     <div class="box-inner"> <div class="faq-controls"> 
      <span id="Expand">Expand FAQs</span> 
     </div></div> 
    </div> 
</div> 
</section> 

這仍然偉大工程。

但是,

我需要的是HTML注入使用jQuery的頁面,所以我颳了一起:

$(function() { 
$('section:nth-child(2)').after('<section class="row m_b_zero"><div class="inner-  container"><div class="box"><div class="box-inner"><div class="faq-controls"><span id="Expand">Expand FAQs</span></div></div></div></div></section>'); 
}); 

這第二<section>標籤後,作爲前注入相同手風琴控制器HTML。

這幾乎可行。

HTML按預期注入,但該按鈕不起作用?它不會打開和關閉手風琴。

我已經確定這個jQuery放在控制手風琴的jQuery之後,它在頁面就緒函數中。

任何人都知道爲什麼它不起作用?

+1

你需要使用'$()。on()'將事件附加到動態添加的元素 – Zword 2014-09-01 17:05:43

回答

1

你給兩個不同的元素相同的id。當你在jQuery中使用一個id選擇器時,它只返回第一個包含id的元素。此外

//HTML 
<span class="Expand">Expand FAQs</span> 

//JS 
$('.Expand').click(function() { 

,如果動態地將其添加到頁面中,你應該考慮event delegation:你應該使用類而不是

$(document).on("click", '.Expand', function() { 
+0

感謝您的推動!明天早上我會看看這個。 – StephenMeehan 2014-09-01 17:51:33

0
  • 一個文檔中的多個元素不能有相同的ID(它是無效的)。您應該改用類名。

  • 您應該爲動態添加的元素委派事件處理程序。假設你使用Expand類,你可以使用on()委派事件處理程序如下:

    $(document).on("click",".Expand", function() { 
        // code 
    }); 
    

document是用於演示目的只,這是更好地使用最接近靜態祖先

+0

謝謝,看起來像()是要走的路。 – StephenMeehan 2014-09-01 17:52:19

相關問題