Creating new elements using jQuery using $ (html, props) and attaching .data

I create a list item on the fly using object notation ( http://api.jquery.com/jQuery/#jQuery2 ) and I would like to be able to add jQuery .data() ( http://api.jquery.com/ data / ).

I have the current code:

 $('<li>', { id: 'filter', text: 'Data Filter 1', click: function() { filter['jQuery_object'] = $(this); filters_display.trigger('remove', filter); } }).appendTo($(this)); 

And I tried this:

 $('<li>', { id: 'filter', text: 'Data Filter 1', load: function() { $(this).data('filter', filter); }, click: function() { filter['jQuery_object'] = $(this); filters_display.trigger('remove', filter); } }).appendTo($(this)); 

But the .load() event doesn't seem to fire when the <li> added to the DOM. Is there a way to do this without selecting a new <li> via its id?

I assumed that it works something like this, returning an array of objects:

 $('<li>', { id: 'filter', text: 'Data Filter 1', data: function() { return [{ key: 'filter', value: filter }] } click: function() { filter['jQuery_object'] = $(this); filters_display.trigger('remove', filter); } }).appendTo($(this)); 
+4
source share
3 answers
 var div = $("<div></div>", { data: { foo: "bar" } }); alert( div.data("foo") ); // => bar 
+4
source

Just add .data('filter', filter) to your chain ...

 $('<li>', { id: 'filter', text: 'Data Filter 1', click: function() { filter['jQuery_object'] = $(this); filters_display.trigger('remove', filter); } }).appendTo($(this)).data('filter', filter); 
+3
source

I asked in the jQuery IRC channel and it is simple as:

 var div = $("<div></div>", { data: { foo: "bar" } }); alert( div.data("foo") ); 

Reply from jQuery IRC channel: http://jsfiddle.net/ehynds/3kw3v/

0
source

All Articles