Jquery将div添加到新div

时间:2013-10-29 09:07:13

标签: javascript jquery html css

我必须将2 div添加到新div:

<script type="text/javascript">
        $(function() {
            $( "#table-filter_wrapper" ).append($( "<div class='main_tbl_btm_info'></div>" ));
            $( "#table-filter_info" ).appendTo( $( ".main_tbl_btm_info" ));
            $( "#table-filter_paginate" ).appendTo( $( ".main_tbl_btm_info" ));
        });
</script>

问题是它准备好找不到 table-filter_wrapper 当我在追加之前使用警报然后它起作用。
如何加载 table-filter_wrapper

4 个答案:

答案 0 :(得分:3)

您需要从$中删除append,如下所示:

<script type="text/javascript">
        $(function() {
            $( "#table-filter_wrapper" ).append( "<div class='main_tbl_btm_info'></div>");
            $( "#table-filter_info" ).appendTo(".main_tbl_btm_info" );
            $( "#table-filter_paginate" ).appendTo( ".main_tbl_btm_info");
        });
</script>

答案 1 :(得分:2)

如果元素在DOM中可用,则代码可以正常运行:http://jsfiddle.net/XY7Sf/

<div id="table-filter_wrapper"></div>
<div id="table-filter_info"></div>
<div id="table-filter_paginate"></div>

如果它们在DOM中不可用,则需要在 时运行此代码,可能在某处的ajax回调中?

答案 2 :(得分:1)

尝试首先定位包装器div或使用.find()来获取要追加的类,如:

var a = $(".wrapper").find(".main_tbl_btm_info")
$( "#table-filter_paginate" ).appendTo(a);

答案 3 :(得分:1)

你想要这样的东西,对吧?

演示JSFIDDLE

JS:

$(function() {
            $( "#table-filter_wrapper" ).append($( "<div class='main_tbl_btm_info'>main_tbl_btm_info</div>" ));

    $( ".main_tbl_btm_info" ).append($( "<div id='table-filter_info'>table-filter_info</div>" ));

    $( ".main_tbl_btm_info" ).append($( "<div id='table-filter_paginate'>table-filter_paginate</div>" ));

});