当存在多个具有相同类的div时,如何将内容加载到唯一的div中

时间:2012-09-12 13:28:42

标签: javascript jquery ajax html

我的HTML布局如下。

            <div class="container">
                // Some contents are here in this level
                <div class="sub-container">
                    // Some contents are here in this level
                    <div class="sub-sub-container">     
                    // Some contents are here in this level
                    ......
                        .....
                            .....
                            .....
                        .....
                    ......
                    </div>
                </div>  
            </div>


        <div class="dynamically_added"> 
            <div class="container">
                // Some contents are here in this level
                <div class="sub-container">
                    // Some contents are here in this level
                    <div class="sub-sub-container">     
                    // Some contents are here in this level
                    ......
                        .....
                            .....
                            .....
                        .....
                    ......
                    </div>
                </div>  
            </div>
        </div>

问题在于,当我尝试更新子容器或子子容器(只是嵌套在主(原始)容器div内部的任何div)时,它正在更新动态添加容器的内容也。如何防止它,以便只更新原始内容?

4 个答案:

答案 0 :(得分:1)

使用jQuery :eq()选择器

jQuery(function(){
    jQuery(".sub-container:eq(0)").html("content for first div"); // for first div
    jQuery(".sub-container:eq(1)").html("content for second div"); // for second div
})

答案 1 :(得分:1)

您可以使用.filter()排除div内的.dynamically_added

var $div = $(".sub-sub-container").filter(function () {
   return $(this).closest(".dynamically_added").length == 0;
});

因此,在您的示例中,这将过滤,每个div匹配div中带有类.dynamically_added的选择器,并包括所有其他人。

<强> DEMO

答案 2 :(得分:1)

var container = $('div[class!="dynamically_added"] > .container');

应该为每个元素提供一个类container而不直接嵌套在div下的dynamically_added

答案 3 :(得分:1)

如果您将额外的类"static"添加到顶部的静态容器中:

<div class="static container">
    // Some contents are here in this level
    <div class="sub-container">
        // Some contents are here in this level
        <div class="sub-sub-container">     
            // Some contents are here in this level
        </div>
    </div>  
</div>

你可以这样做:

$sub_container = $('.static .sub-container');