jQuery: How to store data for non-existent elements?
What is a good approach of storing data for dom elements that do not exist yet, but when cre开发者_开发百科ated they obtain that data.
I'm going make some assumptions here since your question is a little vague at the moment, but it sounds like you want to manipulate DOM elements that do not yet exist, most likely because they will be loaded AJAXily.
jQuery provides a function called .live()
which lets you bind an event handler to all elements that exist now or in the future.
So, if you wanted to add some data to an attribute of all <p>
elements--even those that do not yet exist in the DOM--you could do something like this:
// hook up an event handler that runs anytime a <p> is inserted into the DOM
$('p').live('DOMNodeInserted', function() {
$(this).attr('title', 'foo');
});
// insert a couple <p> elements and see their title attributes update
$('body').append('<p>hello</p>');
$('body').append('<p>world</p>');
Working example: http://jsfiddle.net/rsobers/TLXEu/3/
EDIT: Instead of using attributes to store the data, you can make use of jQuery's .data()
function instead. This is a better place for your custom data.
精彩评论