我的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)时,它正在更新动态添加容器的内容也。如何防止它,以便只更新原始内容?
答案 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');