2014-02-07 89 views
2

我創建一個div動態使用下面的代碼:Javascript:如何隱藏動態創建的div?

$('#pageTabContent').append($('\ 
    <div class="tab-pane" id="'+user_id+'">\ 
     <div class="extras_area">\ 
      <div class="expand_heading">Header to be clicked</div>\ 
      <div class="expandable_content">this should be expanded.</div>\ 
     </div>\ 
    </div>')); 

這是這個HTML內展開:

<div id="right_column"> 
    <ul id="pageTab" class="nav nav-tabs"></ul> 
    <div id="pageTabContent" class="tab-content"></div> 
</div> 

我現在想擴大.expandable_content當我點擊.expand_heading。要做到這一點,我試圖在我的javascript這樣的事情:

$("#right-column").on("load", ".expand_heading", hide); 
$("#right-column").on("click", ".expand_heading", function(){ 
    $(this).next(".expandable_content").slideToggle(100); 
}); 

不幸的是,這是行不通的。動態創建時,我不知道如何正確隱藏div。有人能幫我在這裏嗎?

+0

@ A.Wolff - 不,那是永遠存在的HTML。 – kramer65

+2

我希望「right_column」和「right-column」的區別是錯誤的嗎? :> –

回答

2

工作演示http://jsfiddle.net/t3WVs/

$('#pageTabContent').append($('\ 
    <div class="tab-pane" id="'+Math.random()+'">\ 
     <div class="extras_area">\ 
      <div class="expand_heading">Header to be clicked</div>\ 
      <div class="expandable_content">this should be expanded.</div>\ 
     </div>\ 
    </div>')); 

//$(document).on("load", ".expand_heading", hide); 
$(document).on("click", ".expand_heading", function(){ 
    $(this).next(".expandable_content").slideToggle(100); 
}); 
// if needed default close expand 
// $('.expand_heading').click(); 
+0

請檢查這個[demo](http://jsfiddle.net/t3WVs/1/) – Sender

2

爲什麼不只是使用display:none規則:

$('#pageTabContent').append($('\ 
<div style="display:none;" class="tab-pane" id="'+user_id+'">\ 
    <div class="extras_area">\ 
     <div class="expand_heading">Header to be clicked</div>\ 
     <div class="expandable_content">this should be expanded.</div>\ 
    </div>\ 
</div>'));