Javascript:如何隐藏动态创建的div?

时间:2014-02-07 12:08:31

标签: javascript jquery html css

我正在使用以下代码动态创建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。有人可以帮帮我吗?

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分: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>'));