How to assign custom property to jQuery object?
I need to assign a custom property to a jQuery object. Here is the object:
var object = $("<div id='item'></div>");
I need object
to have a custom data member. How can I add this?
.data()
The .data() function allows you to store or retrieve arbitrary data and associate it with matched elements.
In many situations, it easiest to store key-value-pairs using data() against the body tag.
Data Storage Example
//Store the string "bar" with the body tag, with the key "foo"
$('body').data('foo', 'bar');
Data Retrieval Example
//Retrieve the string "bar"
var str = $('body').data('foo');
Reference
- The Manual
In addition, you can add a property to the DOM object incapsulated in the jQuery object.
You can access the DOM object as the first element of any jQuery object.
var object = $("<div id='item'></div>");
$(object)[0].aproperty = "any value"
精彩评论