I am trying to add new div elements on the fly to an already existing set of elements represented by common class. This set of elements also have a jQuery .data() on it, which I use to do bookkeeping stuff.
The problem is when I try to add the new elements using "before()" the before mentioned .data() values get wiped out. But this is not case with using "after()".
Not sure if this helps but the incoming div element share the same class with the set of existing div elements to which they are being added.
I have created a self-contained example on jsfiddle.
Just toggle the lines between .after() & .before() in the javascript code to know the difference.
I will also paste here the code for easy reference.
HTML Snippet
<div id="pare开发者_Python百科nt-container">
<div id='child1' class="child">I am a child 1 - static</div>
</div>
JavaScript Snippet
$(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"));
});
When you store some data to a selection with .data()
it stores it to all elements in that selection. But when you retrieve it will only select the first one.
Since you put a new one as the first, and you do not store the same data with it, when you try to access the data it returns nothing..
Not sure of your requirements, but you most likely do not have to store the same data to all the .child
elements. Maybe just store it to their common parent, and retrieve it from there as well..
quoting from .data( key )
Description: Returns value at named data store for the first element in the jQuery collection, as set by data(name, value).
精彩评论