开发者

How jQuery $.data() method differs from directly attaching variables to DOM elements?

开发者 https://www.devze.com 2023-03-10 23:46 出处:网络
I can do this: $(\'#someid\').data(\'dataIdentifier\', \'someVariable\'); And in my understanding I can do this:

I can do this:

$('#someid').data('dataIdentifier', 'someVariable');

And in my understanding I can do this:

document.getElementById('someid').dataIdentifier = someVariable;

What are the pros of using jQuery for this versus ra开发者_运维技巧w JavaScript?


From the documentation for jquery.data:

The jQuery.data() method allows us to attach data of any type to DOM elements in a way that is safe from circular references and therefore free from memory leaks. jQuery ensures that the data is removed when DOM elements are removed via jQuery methods, and when the user leaves the page.


I don't know about the jQuery method, but a "pure javascript" approach is to use setAttribute(). setAttribute is the same as what happens when you attach arbitrary data attributes in the html. You can use getAttribute to read it.

document.getElementById('someid').setAttribute("dataIdentifier", "someVariable");

One advantage is that it will show up in the innerHTML property, which plain old properties will not. The disadvantage is you are limited to strings.

0

精彩评论

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