tags:

views:

41

answers:

2

Hi,

I am generating some list items as a result of a search, and I want to attach some data to each list element from the search (possibly a bad idea to merge ui and data), but now curious about it. I am doing this:

var element = $("<li>Hello</li>);
element.mydata = "foo";
element.appendTo("#panelParent");

so I'm just assigning my stuff to element.mydata. My click handler reports that no such data exists for the element when clicked:

$('#panelParent').delegate('li', 'click', function() {
    // this.mydata is undefined.
});

where did it go to? I could keep the data external to the a list item element, was wondering if there's a convenient way like this to just keep it bound though?

Thanks

+1  A: 

You are setting it on the jQuery object, not the DOM element. Do this:

var element = $("<li>Hello</li>");
element[0].mydata = "foo";
element.appendTo("#panelParent");

The standard jQuery way to do this is:

var element = $("<li>Hello</li>");
$(element).data('mydata', 'foo');
// access it
alert( $(element).data('mydata') )

Docs @ http://api.jquery.com/jQuery.data/

meder
And beware of memory leaks in IE6.
SLaks
awesome works great thanks.
A: 

Since you're using jQuery you might as well use jQuery.data() and let the framework deal with browser quirks for you, namely memory leaks in IE6.

Miguel Ventura
thanks right on.