0

I set data with jQuery.data() but I couldn't get it later. Code:

jQuery('#test').live('click', function() {
    alert(jQuery.data($(this), 'key'));
});
var element = jQuery('<div id="test">Test</div>');
jQuery.data(element, 'key', { test: "String" });
jQuery('body').append(element);

I'm using jQuery 1.5. Is this a bug (in jQuery .live()) or am I doing something wrong?

5
  • have you tried to append the div element to body before you set the data? Commented Feb 15, 2011 at 20:01
  • OT: alert sucks, use console.log Commented Feb 15, 2011 at 20:12
  • I use normally console.log but there might be users without a browser with a console (or they deactivated it) so an error could occur. Commented Feb 15, 2011 at 20:14
  • to get around that, use this code: code.google.com/p/fbug/source/browse/branches/firebug1.2/lite/… It will create a mock console object if it doesn't exist that will eliminate those errors. Commented Feb 15, 2011 at 20:27
  • Thanks @Daniel T. but I don't serve code with console code in it to a live site so I don't need that really :) Commented Feb 15, 2011 at 20:57

1 Answer 1

2

Try this instead:

$('#test').live('click', function() {
    alert($(this).data('key'));
});
var element = $('<div id="test">Test</div>');
$(element).data('key', { test: "String" });
$('body').append(element);
Sign up to request clarification or add additional context in comments.

1 Comment

+1, I prefer alert($(this).data('key').test); also element is already a jQuery object. here is a test link ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.