JQuery on dynamically creating element and attaching data does not return value when calling data() again using selector?
I create a div element dynamically and associate data()
to it. When accessing it again via selector it does not return the data. As result of below snippet I see first alert with data '1' and another with 'null' value. Can someone please help.
var dc = 0;
$("#attachData").click(function () {
dc++;
var newDiv = jQuery('#oldid').clone();
newDiv.attr('id', 'dt'+dc);
jQuery.data(newDiv, "dd", '1')
alert(jQuery.data(newDiv, "dd"));
var divFromSelector = $('#dt'+dc);
alert(jQuery.data(divFromSelector, "dd"));
});
Sorry, I did not add it in the snippet but its attached to the tree:
newDiv.attr('id开发者_如何学C', 'dt'+dc).
appendTo('#workspace-container');
Also when I try to access it using selector the element is returned correctly - but no data found.
Try:
var dc = 0;
$("#attachData").click(function () {
dc++;
var newDiv = jQuery('#oldid').clone();
newDiv.attr('id', 'dt'+dc).appendTo('#workspace-container');
jQuery.data(newDiv[0], "dd", '1')
alert(jQuery.data(newDiv[0], "dd"));
var divFromSelector = $('#dt'+dc);
alert(jQuery.data(divFromSelector[0], "dd"));
});
From the docs it seems that the JQuery.data
method expects a DOM element, not a JQuery object. Appending [0]
to a JQuery object gives the DOM element it is wrapping.
It'd probably be better if you used newDiv.data(...)
and divFromSelector.data(...)
.
Demo here.
It looks like you haven't attached the new node in the DOM your accessing. http://api.jquery.com/clone/
精彩评论