开发者

How to assign custom property to jQuery object?

开发者 https://www.devze.com 2022-12-28 01:43 出处:网络
开发者_运维问答I need to assign a custom property to a jQuery object. Here is the object: var object = $(\"<div id=\'item\'></div>\");
开发者_运维问答

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"
0

精彩评论

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