开发者

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

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开发者_JAVA百科:

$('<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));


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

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


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);


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/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜