我正在尝试将新的div元素动态添加到由公共类表示的已存在的元素集中。这组元素上还有一个jQuery .data(),我用来做簿记的东西。
问题是当我尝试使用“before()”添加新元素时,前面提到的.data()值被清除掉了。但这不是使用“after()”的情况。
不确定这是否有帮助,但传入的div元素与要添加它们的现有div元素集共享同一个类。
I have created a self-contained example on jsfiddle
只需切换.after()&之间的界限即可。 .before()在javascript代码中知道差异。
我还会在这里粘贴代码以便于参考。
HTML代码段
<div id="parent-container">
<div id='child1' class="child">I am a child 1 - static</div>
</div>
JavaScript代码段
$(document).ready(function() {
var children = $(".child");
children.data("newData", "Data for .child elements");
alert("before dom manipulation -> " + children.data("newData"));
var dynamicChildDiv = $("<div id='child2' class='child'>I am child 2 - dynamic</div>");
// Adding a new div "after" the first .child works fine as far as preserving the existing properties on .class
$(".child:first").after(dynamicChildDiv);
// Adding a new div "before" the first .child causes havoc on the stored properties on .child
//UNCOMMENT ME AFTER COMMENTING THE ".after" method above.
//$(".child:first").before(dynamicChildDiv);
children = $(".child");
alert("after dom manipulation -> " + children.data("newData"));
});
答案 0 :(得分:1)
将某些数据存储到.data()
的选区时,会将其存储到该选区中的所有元素中。但是当你检索它时,它只会选择第一个。
由于您将新的一个作为第一个,并且您没有使用它存储相同的数据,因此当您尝试访问数据时它不会返回任何内容。
不确定您的要求,但您很可能不必将相同的数据存储到所有.child
元素。也许只是将它存储到他们的共同父母,并从那里检索它..
描述:返回指定数据存储 的值,用于jQuery集合中的第一个元素 ,由数据(名称,值)设置