tags:

views:

25

answers:

3

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

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 have 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 does not seem to be triggered when the <li> is appended to the DOM. Is there a way to accomplish this without selecting the new <li> via it's id?

I envisaged it working something like this by 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));
+2  A: 

Simply 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);
Sean Vieira
That will attach the data to $(this) and not the li won't it?
Treffynnon
@Treffynnon -- nope, `appendTo()` will still return the newly created `<li>` -- see: http://jsfiddle.net/wrwfG/
Sean Vieira
+2  A: 
var div = $("<div></div>", {
    data: {
        foo: "bar"
    }
});

alert( div.data("foo") ); // => bar
ehynds
A: 

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

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

alert( div.data("foo") );

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

Treffynnon
The accepted answer is from the same person who helped in the IRC channel.
Treffynnon