最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - an alternative to hiding data in divs? - Stack Overflow

programmeradmin0浏览0评论

All too often I find myself storing object data in hidden dom elements. I was curious if there was a way to attach this data to the dom node itself. When I try to create attributes 'on the fly', it doesn't seem to work. It would be much easier to access the property with this.something instead of accessing the html contained in a child. I feel like I should know how to do this, but I don't. Thanks.

All too often I find myself storing object data in hidden dom elements. I was curious if there was a way to attach this data to the dom node itself. When I try to create attributes 'on the fly', it doesn't seem to work. It would be much easier to access the property with this.something instead of accessing the html contained in a child. I feel like I should know how to do this, but I don't. Thanks.

Share Improve this question asked Feb 4, 2011 at 0:02 Brandon FrohbieterBrandon Frohbieter 18.1k3 gold badges41 silver badges62 bronze badges 3
  • As already mentioned, jQuery.data is probably what you are looking for. That said, look into the html5 specs and the data- attributes, which are pretty awesome, and something that you will see used already on many sites, since they don't break in non html5 browsers :) – Martin Jespersen Commented Feb 4, 2011 at 0:08
  • Not sure why adding attributes 'on the fly' isn't working for you. Have a look at this example to see how to make it work (webdevout/test?01o) – nybbler Commented Feb 4, 2011 at 0:11
  • thanks nybbler, guess I hadn't tried it that way. – Brandon Frohbieter Commented Feb 4, 2011 at 0:13
Add a ment  | 

2 Answers 2

Reset to default 9

There absolutely is! jQuery's .data().

$('#someId').data('myData', someValue); // To store the data
$('#someId').data('myData'); // To retrieve it again

Any JavaScript variable can be stored as data - it's not limited to strings.

Note that this doesn't actually attach data to the DOM node as you say (which should be avoided). jQuery keeps its own cache of all the data you store and the DOM nodes you wanted to attach it to. So, it's not the same as domNode.myData = someValue.

jQuery.data is the preferred way of doing this.

发布评论

评论列表(0)

  1. 暂无评论